← 中文资源

简体中文版本

await 与 thenable 的互操作

await 与 Promise.resolve 都能解包 thenable:带 then 方法的对象像 promise 一样被等待,重复 resolve 只取第一次。

阅读英文原文

实现说明

异步流被 await 线性化,失败处理保持局部。 演示用的数据放在这几个模块级绑定中:lazy、wrapped、calls、noisy。

使用要点

  • 演示输出是带标签的(awaited thenable:、resolved thenable:、unwrapped once:),每个操作都会留下自己的一行标注。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 文件用顶层绑定保存自己的状态:lazy、wrapped、calls。

核心语句

const wrapped = Promise.resolve({ then: (resolve) => resolve(41) });
setTimeout(() => resolve('computed later'), 5);

代码示例

// thenable:任何带 then(resolve, reject) 方法的对象都能被 await 解包
const lazy = {
  then(resolve) {
    setTimeout(() => resolve('computed later'), 5);
  },
};

console.log('awaited thenable:', await lazy);

// Promise.resolve 对 thenable 同样逐层解包
const wrapped = Promise.resolve({ then: (resolve) => resolve(41) });
console.log('resolved thenable:', await wrapped);

// 重复调用 resolve 只取第一次,与 promise 语义一致
let calls = 0;
const noisy = {
  then(resolve) {
    calls += 1;
    resolve('first only');
    resolve('second ignored');
  },
};
console.log('unwrapped once:', await noisy, '| then calls:', calls);