JavaScript Promises

Embed Size (px)

Text of JavaScript Promises

  • JAVASCRIPT PROMISES in

    ECMAScript6 (Harmony)

  • 01 02 03 04

    Promise ?

    Promise

    Promise

    Promise

    Promise

    .

    Promise

    ,

    thenable

    .

    Promise

    .

    ES6 Promises

    Promise/A+

    Promise

    .

    2

  • 1

    3

    try{ setTimeout(function(){ throw new Error(' .'); }, 1000); }catch(err){ console.error(err); console.log(' .'); }

  • 1

    try{ setTimeout(function(){ throw new Error(' .'); }, 1000); }catch(err){ console.error(err); console.log(' .'); }

    global

    4

  • 1

    try{ setTimeout(function(){ throw new Error(' .'); }, 1000); }catch(err){ console.error(err); console.log(' .'); }

    global setTimeout() handler

    5

  • 1

    try{ setTimeout(function(){ throw new Error(' .'); }, 1000); }catch(err){ console.error(err); console.log(' .'); }

    global time event setTimeout() handler

    6

  • 1

    try{ setTimeout(function(){ throw new Error(' .'); }, 1000); }catch(err){ console.error(err); console.log(' .'); }

    global time event setTimeout() handler

    7

  • 1

    try{ setTimeout(function(){ throw new Error(' .'); }, 1000); }catch(err){ console.error(err); console.log(' .'); }

    global time event setTimeout() handler

    8

  • 2

    fs.readdir(source, function(err, files){ if(err){ console.log('Error finding files : ' + err); }else{ file.forEach(function(filename, fileIndex){ console.log(filename); gm(source + filename).size(function(err, vlaues){ if(err){ console.log('Error identifying file size : ' + err); }else{ console.log(filename + ' : ' + values); aspect = (values.width / value.height); widths.forEach(function(width, wwidthIndex){ height = Math.round(width /aspect); console.log('resizing ' + filename + 'to ' + height + 'x' + height); this.resize(width, height).write(

    destination + 'w' + width + '_' + filename, function(err){ if(err){ console.log('Error writing file : ' + err); } } ); }); } }); }); } })

    9

  • Promise?

    Promise .

    E .

    10

  • Promise?

    .

    .

    Promise .

    .

    11

  • Promise?

    ES6 DRAFT

    Promises/A+

    https://github.com/domenic/promises-unwrapping

    https://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-constructor

    Promises/A+ : https://promisesaplus.com/

    12

  • Promise?

    if('serviceWorker' in navigator){ navigator.serviceWorker.register('/sw=text/sw.js', { scope: '/' }).then(function(sw){ // registration worked console.log('Registration succeeded.'); }).catch(function(err){ // registration filed console.log('Registration filed with ' + err); }) }

    function writeArrayToStream(array, writableStream){ array.forEach(chunk = > writableStream.write(chunk)); return writableStream.close(); } writeArrayToStream([1, 2, 3, 4, 5], writableStream) .then(() => console.log('All done!')) .catch(e => console.log('Error with the stream : ' + e));

    Service Worker API

    Streams API

    13

  • Promise Promises API

    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

    strawman() : http://wiki.ecmascript.org/doku.php?id=strawman:promises

    Constructor

    var promise = new Promise(function(resolve, reject){ // // resolve reject });

    Instace Method Static Method

    Promise.prototype.then(onFulfilled, onRejected)

    Promise.prototype.catch(onRejected)

    Promise.all()

    Promise.race()

    Promise.resolve()

    Promise.reject() 14

  • Promise

    /** * @returns {Promise} */ function asyncFunction(){ return new Promise(function(resolve, reject){ setTimeout(function(){ resolve('Async Hello world!!'); }, 16); }) }

    asyncFunction().then(function(value){ console.log(value); }).catch(function(error){ console.log(error); });

    asyncFunction().then(function(value){ console.log(value); }, function(error){ console.log(error); });

    asyncFunction() Promise Promise . then(), catch() . catch() then() .

    15

  • Promise

    ( )

    ( )

    unresolved Pending,

    has-resolution Fulfilled, (resolve)

    has-rejection Rejected, (reject)

    Settled, .

    Fullled

    Rejected

    Pending

    16

  • Promise

    1. new Promise(fn) promise . 2. fn .

    resolve( ) . reject(error) .

    function getJSON(URL){ return new Promise(function(resolve, reject){ var req = new XMLHttpRequest(); req.open('GET', URL, true); req.onload = function(){ if(req.status === 200){ resolve(JSON.parse(req.responseText)); }else{ reject(new Error(req.statusText)); } }; req.onerror = function(){ reject(new Error(req.statusText)); }; req.send(); }) }

    function doSomething(callback){ var value = 42; if(value === 42){ callback(null, value); }else{ callback(new Error(''), null); } }

    17

  • Promise

    Promise .

    Pending

    18

  • Promise

    Promise .

    resolve() , Fulfilled onFulfilled .

    onFullled

    resolve() value

    Pending

    19

  • Promise

    Promise .

    resolve() , Fulfilled onFulfilled .

    reject() , Rejected onRejected .

    onRejected

    reject() error

    Pending

    20

  • Promise

    Promise .

    resolve() , Fulfilled onFulfilled .

    reject() , Rejected onRejected .

    onRejected

    reject() error

    onFullled

    resolve() value

    getJSON('/api/stores').then(function(value){ console.log(value); }).catch(function(error){ console.log(error.message); });

    getJSON(/api/stores').then(function(value){ console.log(value); }, function(error){ console.log(error.message); });

    Pending

    21

  • PROMISES

  • Promise.resolve new Promise()

    Promise.resolve() new Promise() .

    23

  • Promise.resolve new Promise()

    Promise.resolve() new Promise() .

    var promise = new Promise(function(resolve){ resolve(42); }).then(function(value){ console.log(value); });

    var promise = Promise.resolve(42).then(function(value){ console.log(value); });

    24

  • Promise.resolve thenable resolve

    then() promise thenable . Promise.resolve() thenable promise . ( Promise.cast() .)

    25

  • Promise.resolve thenable resolve

    then() promise thenable . Promise.resolve() thenable promise . ( Promise.cast() .)

    26

    var promise = Promise.resolve($.ajax('/api/comments')); promise.then(function(value){ console.log(value); }).catch(function(error){ console.log(error.statusText); });

    : jQuery.ajax() jqXHR Deferred Object . Deferred Promise/A+ ES6 Promise .

  • Promise.reject new Promise()

    Promise.reject() new Promise() .

    27

    var promise = new Promise(function(resolve, reject){ reject(new Error('')); }).catch(function(error){ console.log(error.message); });

    Promise.reject(new Error('')).catch(function(error){ console.log(error.message); });

  • Promise.prototype.then

    promise then() catch() . .

    28

  • Promise.prototype.then

    promise then() catch() . .

    29

    function taskA(){ console.log('Task A'); } function taskB(){ console.log('Task B'); } function onRejected(error){ console.log('Catch Error: A or B', error); } function finalTask(){ console.log('Final Task'); } var promise = Promise.resolve(); promise.then(taskA) .then(taskB) .catch(onRejected) .then(finalTask);

    TaskA

    TaskB

    FinalTask

    onRejected

  • Promise.prototype.then

    TaskA TaskB onRejected finalTask .

    30

    function taskA(){ console.log('Task A'); throw new Error('throw Error @ Task A'); } function taskB(){ console.log('Task B'); } function onRejected(error){ console.log('Catch Error: A or B', error); } function finalTask(){ console.log('Final Task'); } var promise = Promise.resolve(); promise.then(taskA) .then(taskB) .catch(onRejected) .then(finalTask);

    TaskA

    TaskB

    FinalTask

    onRejected

    function taskA(){ console.log('Task A'); return Promise.reject(new Error()); }

  • Promise.prototype.then

    onFulfilled onFulfilled