Await Accepts Thenables Like Promises
Await any object with a then method: Promise.resolve and await unwrap thenables, and repeated resolve calls only take the first one.
Code
// 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);How it works
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Top-level bindings lazy, wrapped, calls, noisy hold the demo state — nothing sits inside a function scope.
Putting it to use
The demo output is labeled (awaited thenable:, resolved thenable:, unwrapped once:), so every printed line maps back to its originating operation.
Core lines
const wrapped = Promise.resolve({ then: (resolve) => resolve(41) });
setTimeout(() => resolve('computed later'), 5);
Interactive Tools for This Topic
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Its state lives in module-level bindings: `lazy`, `wrapped`, `calls`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.