How to write async/await in vanilla JS

Viewed 1272

In the MDN Doc, it says

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.

Would it be

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

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. So the equivalent is:

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