Why await only works in async function in javascri

2019-06-24 15:51发布

Just going through this tutorial, and it baffles me to understand why await only works in async function.

From the tutorial:

As said, await only works inside async function.

From my understanding, async wraps the function return object into a Promise, so the caller can use .then()

async function f() {
  return 1;
}

f().then(alert); // 1

And await just waits for the promise to settle within the async function.

async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // wait till the promise resolves (*)

  alert(result); // "done!"
}

f();

It seems to me their usage are not related, could someone please explain?

1条回答
欢心
2楼-- · 2019-06-24 15:56

async and await are both meta keywords that allow asynchronous code to be written in a way that looks synchronous. An async function tells the compiler ahead of time that the function will be returning a Promise and will not have a value resolved right away. To use await and not block the thread async must be used.

async function f() {
    return await fetch('/api/endpoint');
}

is equivalent to

function f() {
    return new Promise((resolve,reject) => {
        return fetch('/api/endpoint')
        .then(resolve);
    });
}
查看更多
登录 后发表回答