Promise.resolve()

问题

以下代码执行结果是?

Promise.resolve({
  then: function () {
    console.log('a');
  }
}).then(() => {
  console.log('d');
});

首先第一直觉就是打印 d,当结果却是 a。立马去翻了 MDN ,果然发现了一些细节上的问题。
当传入对象是一个 thenable 时,相当于返回一个新的 Promise 对象,状态依赖于该对象 then 方法。

Promise.resolve({ then: () => {} }).then(() => console.log('object'));
// output:
// 整个 Promise.resolve({ then: () => {} }) 返回状态处于 pending

Promise.resolve({ then: res => res() }).then(() => console.log('object'));
// output: object

Promise.resolve('object').then(res => console.log(res));
// output: object

let a = Promise.resolve('object');
Promise.resolve(a).then(res => console.log(res));
// output: object
// 参数时 promise 对象,直接返回该 promise

let a = Promise.resolve('object');
let b = Promise.resolve(a);
Promise.resolve(b).then(res => console.log(res));
// output: object
// 参数是嵌套 promise 对象,返回展平后的 promise

总结

  • 返回值一定是一个 Promise 对象;
  • 如果参数是一个 Promise 对象,则返回这个这个对象;
  • 如果参数是一个多层嵌套 Promise 对象,则返回展平的 Promise 对象;
  • 如果参数是一个 thenable,则返回 Promise 状态跟随这个 thenable 对象;
  • 否则返回一个以该参数完成的 Promise

  1. 带有 then 方法,这个方法的参数分别是 resolvereject↩︎

posted @   梦渊同学  阅读(158)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示