'use strict';
let p1 = Promise.resolve('p1-resolve');
let p2 = p1.then(
() => Promise.resolve('p2-resolve'),
() => {}
)
.then(
() => setTimeout(console.log, 0, 'resolve'),
() => setTimeout(console.log, 0, 'reject')
);
setTimeout(console.log, 0, p1);
setTimeout(console.log, 0, p2);
在 Firefox 主控台顯示:
Promise { <state>: "fulfilled", <value>: "p1-resolve" }
Promise { <state>: "fulfilled", <value>: 4 }
resolve
請問:
我預期 p2 顯示的值是 "p2-resolve",
但為何卻是 4 呢?
因為最後的 then 回傳的是
setTimeout(console.log, 0, 'resolve')
所以那個 4 是 setTimeout
的回傳值 timeoutID
參考setTimeout()#Return value
如果是下面這樣,就會得到你想要的結果
let p1 = Promise.resolve('p1-resolve');
let p2 = p1.then(
() => {
setTimeout(console.log, 0, 'resolve')
return Promise.resolve('p2-resolve');
},
() => {}
)
setTimeout(console.log, 0, p1);
setTimeout(console.log, 0, p2);
Promise {<fulfilled>: 'p1-resolve'}
Promise {<fulfilled>: 'p2-resolve'}
resolve