Promise再入門(2)
Promiseのthen()メソッドをコールすることは、既存のpromiseにハンドラをアサインするだけでなく新しいpromiseを作ることである。
const newPromise = promise.then(handleSuccess, handleRejection)
Promiseチェーン
successまたはerrorハンドラがpromiseを返すとき、then()メソッドはそのpromiseがresolveするまで待ち、渡された値を返却されたpromiseに対して使う。詳しくは以下の例を見れば一目瞭然。
const addOneByOne = data => ( new Promise(resolve => { setTimeout( () => resolve(data + 1), Math.random() * 1000 ) }) ) addOneByOne(1) .then(result => { console.log('1st then handler:', result) // 1st then handler: 2 return addOneByOne(result) }) .then(result => { console.log('2nd then handler:', result) // 2nd then handler: 3 return addOneByOne(result) }) .then(result => { console.log('3rd then handler:', result) // 3rd then handler: 4 })
setTimeoutで実行タイミングをズラしたとしても、順番通りに処理が行われていることがわかる。
これは、thenオブジェクトでreturnを行わなくても同じ結果になる。
addOneByOne(1) .then(result => { console.log('1st then handler:', result) // 1st then handler: 2 }) .then(result => { console.log('2nd then handler') // 2nd then handler }) .then(result => { console.log('3rd then handler') // 3rd then handler })
CallbackをPromiseにリファクタする例
作った