setTimeout 使用 async-await 关键字但不知道它是如何工作的

setTimeout working with async-await keywords but don't know how it works

我正在使用 javascript 编程,我无意中发现了这段代码我想知道下面的代码如何工作以及为什么工作:

var test = async () => {
  console.log("before");
  await setTimeout(() => {
    console.log("after");
  }, 1000);

};
test();

记录是这样的:

  1. "before"
  2. "after"

这是一个示例代码,但我的问题是它是如何工作的? setTimeout() 没有 return Promise(我认为)所以 async/await 对不应该工作或者我缺少什么?

根据MDN Web Docs

If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise.

因此,await setTimeout 表达式被转换为已解析的 Promise。

嗯,它有效:

async function test() {
  console.log("before");
  await setTimeout(() => {
    console.log("callback");
  }, 1000);
  console.log("after");
}
test();

您将收到 before - after - callbackawait 不会阻止任何事情,因为 - 如您所知 - setTimeout 不会 return 承诺。它等待 undefined 并继续执行下一条语句。你的例子只是缺少下一条语句,所以你看不出有什么不同。这是一个工作示例:

function delay(t) {
    return new Promise(resolve => setTimeout(resolve, t));
}
async function test() {
  console.log("before");
  await delay(1000);
  console.log("after");
}
test();