Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Promise

 Promise

howdy39

June 15, 2018
Tweet

More Decks by howdy39

Other Decks in Programming

Transcript

  1. Promiseの基本 // Promiseオブジェクトを作成 const promise = new Promise((resolve, reject) =>

    { // 何らかの処理(非同期処理) if (解決時) { resolve('解決'); } else { reject(new Error('棄却')); } });
  2. Promiseの基本 const promise = new Promise((resolve, reject) => { /*

    省略 */ }); // Promiseオブジェクトの結果により処理を実行 promise .then(value => { console.log('then', value); // resolve()が呼ばれた場合 }) .catch(value => { console.log('catch', value); // reject()が呼ばれた場合 });
  3. 次のPromiseに値を渡す(fetchをreturn) Promise.resolve() .then(() => { console.log('aaa'); return fetch('https://api.github.com/orgs/topgate'); }) .then(response

    => { console.log('bbb'); return response.json(); // Response#json()はPromiseを返す }) .then(json => console.log('ccc', json));
  4. Promise.all([ new Promise(resolve => { console.log('aaa'); resolve(); }), new Promise(resolve

    => { console.log('bbb'); resolve(); }), ]).then( () => console.log('ccc'), // 解決時の処理 ).catch( (error) => console.log('ddd', error) // 棄却時の処理; );
  5. Promise.race([ new Promise(resolve => { console.log('aaa'); resolve(); }), new Promise(resolve

    => { console.log('bbb'); reject(new Error('bbb error')); }), ]).then( () => console.log('ccc'), // 解決時の処理 ).catch( (error) => console.log('ddd', error) // 棄却時の処理; );
  6. 参考 JavaScript Promiseの本 http://azu.github.io/promises-book Promise | MDN https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Promise Promise.prototype |

    MDN https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Promise/prototype 今更だけどPromise入門 https://qiita.com/koki_cheese/items/c559da338a3d307c9d88 JavaScript の Promise https://developers.google.com/web/fundamentals/primers/promises