Promise
Promiseチェーン
非同期処理の結果を次の非同期処理で使うとき、以下のようにコールバック地獄となる。
doSomething(function(result) { doSomethingElse(result, function(newResult) { doThirdThing(newResult, function(finalResult) { console.log('Got the final result: ' + finalResult); }, failureCallback); }, failureCallback); }, failureCallback);
Promiseであれば、以下のようにかける。
doSomething().then(function(result) { return doSomethingElse(result); }) .then(function(newResult) { return doThirdThing(newResult); }) .then(function(finalResult) { console.log('Got the final result: ' + finalResult); }) .catch(failureCallback);
関数をPromiseでラップする
Promiseチェーンを繋げられるようにする
const fs = require('fs') function readFileAsync(file) { return new Promise((resolve, reject) => { fs.readFile(file, (err, data) => { if (err) { reject(err) // 失敗したとき } resolve(data) // 成功したとき }) }) }
Promise.resolve()
resolveを呼びだすショートカット
function onFulfilled(data) { console.log(data) return Promise.resolve(data) } readFileAsync(module.filename) .then(onFulfilled) .then(data => { console.log(data.toString()) })