promise 相关题目
then 方法里直接返回数字和返回 Promise.resolve 的区别
下面这道题会打印 0、1、2、3、4、5、6。
结论:then 方法里返回 promise 和返回非 promise,表现会不一样。
html
<!DOCTYPE html>
<body>
<script>
Promise.resolve().then(() => {
console.log(0)
// return Promise.resolve(4)
return new Promise(resolve => {
resolve(4)
})
}).then(res => {
console.log(res)
})
Promise.resolve().then(() => {
console.log(1)
}).then(() => {
console.log(2);
})
.then(() => {
console.log(3);
}).then(() => {
console.log(5);
}).then(() => {
console.log(6);
})
</script>
</body>
</html>如果改成这样,就会打印 0、1、4、2、3、5、6 了。
html
<!DOCTYPE html>
<body>
<script>
Promise.resolve().then(() => {
console.log(0)
return 4
}).then(res => {
console.log(res)
})
Promise.resolve().then(() => {
console.log(1)
}).then(() => {
console.log(2);
})
.then(() => {
console.log(3);
}).then(() => {
console.log(5);
}).then(() => {
console.log(6);
})
</script>
</body>
</html>原因分析
一个 then 函数里返回一个 Promise,确实会将下一个 then 函数推入微任务队列。但是下一个 then 函数发现上一个 then 函数返回的值是一个 Promise 类型的数据,会使用该数据的 .then 方法拿到该 Promise 的值。