Why await only works in async function in javascript?

↘锁芯ラ 提交于 2020-01-03 08:49:10

问题


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:


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);
    });
}


来源:https://stackoverflow.com/questions/49640647/why-await-only-works-in-async-function-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!