为什么await只能在javascript中的异步函数中工作?

问题描述 投票:0回答:2

刚刚看完这个教程,我很困惑为什么

await
只适用于
async
函数。

来自教程:

如前所述,await 只能在异步函数中工作。

根据我的理解,

async
将函数返回对象包装成Promise,因此调用者可以使用
.then()

async function f() {
  return 1;
}

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

并且

await
只是等待承诺在
async
函数中解决。

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

在我看来他们的用法不相关,有人可以解释一下吗?

javascript asynchronous async-await
2个回答
19
投票

代码在
await
上变为异步 - 我们不知道要返回什么

除了等待 Promise 解决之外,

await
还做的是立即1 将代码执行返回给调用者。
await
之后函数内的所有代码都是异步的。

  • async
    是用于返回承诺的语法糖。
  • 如果您不想在
    await
    返回承诺,异步代码中明智的替代方案是什么?

我们看下面的错误代码,看看返回值的问题:

function f() {
  // Execution becomes asynchronous after the next line, what do we want to return to the caller?
  let result = await myPromise;

  // No point returning string in async code since the caller has already moved forward.
  return "function finished";
}

我们可以问另一个问题:为什么我们没有一个同步版本的

await
,它不会将代码更改为异步?

我的看法是,出于很多充分的原因,使异步代码同步在设计上变得很困难。例如,在等待异步函数执行时,人们很容易意外地使整个应用程序冻结。返回。


async
await
进一步说明运行时顺序:

async function f() {
    
  for(var i = 0; i < 1000000; i++); // create some synchronous delay

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

  console.log("message inside f before returning, still synchronous, i = " + i);

  // let's await and at the same time return the promise to the caller
  let result = await promise;
  console.log("message inside f after await, asynchronous now");

  console.log(result); // "done!"

  return "function finished";
}

let myresult = f();
console.log("message outside f, immediately after calling f");

控制台日志输出为:

message inside f before returning, still synchronous, i = 1000000 
message message outside f, immediately after calling f 
message inside f after await, asynchronous now 
done!

1 关于即时性的更正:一旦获得 Promise,它就会将代码执行返回给调用者,这种情况发生在调用链中较高位置显式等待 Promise 或等待的异步函数返回时。

因此

const xxx = async () => { /* when this returns, the call chain becomes async */ }
const xx = async () => {
    /* synchronous delay can be created here to make a point */
    console.log("inside before");
    await xxx();
    console.log("inside after")
}
const x = async () => await xx();
x();
console.log("outside");

打印

inside before
outside
inside after

3
投票

async
await
都是元关键字,允许以“看起来”同步的方式编写异步代码。 async 函数提前告诉编译器该函数将返回
Promise
并且不会立即解析值。要使用
await
并且不阻塞线程
async
必须使用
async function f() { return await fetch('/api/endpoint'); }

相当于

function f() { return new Promise((resolve,reject) => { return fetch('/api/endpoint') .then(resolve); }); }


© www.soinside.com 2019 - 2024. All rights reserved.