简体   繁体   English

如何在 vanilla JS 中编写 async/await

[英]How to write async/await in vanilla JS

In the MDN Doc , it saysMDN Doc中,它说

async function foo() { 
    await 1
}

is equivalent to:相当于:

function foo() {
    return Promise.resolve(1).then(() => undefined)
}

so what is the eqivalent of那么什么是等价的

async function foo() {
    await genPromise();
}

assuming that genPromise() returns another Promise.假设 genPromise() 返回另一个 Promise。

Would it be可不可能是

function foo() {
    return Promise.resolve(new Promise((resolve, reject) => {})).then(() => undefined)
}

so what is the eqivalent of那么什么是等价的

async function foo() { await genPromise(); }

That code will wait for the promise returned by genPromise to resolve, and then will resolve its own promise to undefined .该代码将等待 genPromise 返回的 promise 解析,然后将其自己的 promise 解析为undefined So the equivalent is:所以等价的是:

function foo() {
  return genPromise().then(() => undefined);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM