非同期処理を学ぶ Promise, resolve, reject, then, catch, finally, 成功, 失敗
ハンズオンJavaScript (あんどうやすし(著)、オライリー・ジャパン)の10章(非同期処理を学ぶ)、10.4(練習問題)の10-1の解答を求めてみる。
コード
let result = [];
Promise.resolve(42)
.then(() => result.push('first'))
.catch(() => result.push('first catch'))
.then(() => result.push('second'))
.then(() => {
result.push('first error')
return Promise.reject()
})
.then(() => 'third')
.then(() => result.push('fourth'))
.catch(() => result.push('second catch'))
.then(() => result.push('fifth'))
.catch(() => result.push('third catch'))
.finally(() => {
result.push('first finally')
for (let value of result) {
console.log(value);
}
console.log(
result.join('\n') === [
'first',
'second',
'first error',
'second catch',
'fifth',
'first finally',
].join('\n')
);
});
入出力結果(Terminal, Zsh)
% node main.js
first
second
first error
second catch
fifth
first finally
true
%