Geo*_*rge 4 javascript event-loop async-await
来自 MDN
异步函数通过事件循环以与其余代码不同的顺序运行,
但是,我不明白这对于一个不显式返回任何内容并且根本不使用 await 的简单函数意味着什么。在这种情况下声明一个函数 async 有什么用吗?它是否会在稍后执行以允许页面响应,例如在执行时?我的测试表明它是同步执行的,根本没有延迟:
async function foo() {
console.log('Start heavy stuff');
for (let i = 0; i < 90000000; ++i) {
Math.random()
}
console.log('Fnish heavy stuff')
}
foo();
console.log('All done, synchronously');Run Code Online (Sandbox Code Playgroud)
日志按预期顺序显示,那么在这种情况下可以使用使此函数异步吗?这与使用 调用此函数有任何相似之处setTimeout(foo, 0)吗?
async函数同步运行,直到到达第一个await或return,抛出错误,或者代码执行刚好在函数结束时运行(就像在您的函数中一样)。在这一点上,该函数返回一个承诺。
async在这种情况下声明一个函数有什么用吗?
不是在那个特定的情况下,不是。该函数似乎没有任何理由返回承诺,并且正如您在测试中看到的那样,它的所有工作都是同步完成的。
它是否会在稍后执行以允许页面响应,例如在执行时?
不。
async当函数不使用await. 它使它返回一个承诺,但除此之外不做任何其他事情。也许如果你打算在承诺链中使用它,但是......
下面是async函数如何同步运行的一个稍微不同的例子:
async function example1() {
console.log("this is done synchronously");
await Promise.resolve();
console.log("this is done asynchronously");
}
console.log("before calling example1");
example1().then(() => {
console.log("promise from example1 was fulfilled");
});
console.log("after calling example1");Run Code Online (Sandbox Code Playgroud)
输出:
在调用example1之前 这是同步完成的 调用example1后 这是异步完成的 来自 example1 的承诺已兑现