console.log("1");
console.log("2");
async function a() {
for (let i = 0; i < 1000000000; i++) {}
for (let i = 0; i < 1000000000; i++) {}
}
a().then(() => console.log("in then"));
console.log("3!");
我想要的输出是这样的 1个 2个 3! 在那时
但是异步函数的行为是同步的,不会让 3!打印直到长循环完成执行。我想如果使用 async 关键字,它会在后台运行里面的函数? 我基本上希望 2 个长循环在后台运行。只是想了解异步和等待。 谢谢。
编辑: 有人能告诉我为什么这也同步工作吗??
console.log("2");
function lag(resolve) {
for (let i = 0; i < 1000000000; i++) {}
for (let i = 0; i < 1000000000; i++) {}
console.log("in lag");
return resolve;
}
async function a() {
// console.log("its done");
let a = await new Promise((resolve, reject) => lag(resolve));
}
a().then(() => console.log("in then"));
console.log("3!"); ```
最佳答案
async
函数(或 promises)没有任何东西可以在后台运行。他们不会创建新线程或类似的东西。
async
函数在第一个 await
或 return
之前是同步的。由于您的函数没有任何 await
或 return
,因此它是完全同步的。
promises 的目的是观察已经异步完成的事情,例如浏览器通过 HTTP 或计时器加载内容。 async
函数的目的是提供使用 promises 的语法,让我们编写代码的逻辑流程而不是编写回调函数。它们都不会使任何事情异步,或将事情移动到不同的线程。
如果你想在后台运行一些东西,你可以创建一个工作线程并通过消息传递在它和主线程之间交换信息。在浏览器上它是 web workers .在 Node.js 中它是 worker threads模块。
在您的问题和对答案的评论中,您谈到了 async
函数似乎如何等待异步任务完成。事实上,函数的逻辑确实如此。但这确实是使用 promises 的语法糖(真的,非常好的语法糖,恕我直言)。让我们看一下 async
函数:
function delay(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
async function example() {
// The function starts out synchronous, so that it can
// start whatever inherently-asynchronous thing it does
// (like calling `fetch`).
console.log("[example] This is synchronous");
// When execution reaches the first `await` or `return`,
// the `async` function returns a promise. The synchronous
// part of its work is now complete.
await delay(10);
// This code runs later, when/if the promise from `delay`
// is settled.
console.log("[example] This is asynchronous, but still on the main thread");
// If you `throw` in an `async` function, it rejects the `async`
// function's promise.
if (Math.random() < 0.5) {
throw new Error("Error thrown by `example`");
}
// The "return" value of an `async` function is the fulfillment
// value of the promise the `async` function returned
return 42;
}
console.log("[top] Calling `example`...");
const promiseFromExample = example();
console.log("[top] Back from calling `example`. Waiting for its promise to settle.");
promiseFromExample
.then((value) => {
console.log(`[top] The promise from \`example\` was fulfilled with the value ${value}`);
})
.catch((reason) => {
console.log(`[top] The promise from \`example\` was rejected with the rejection reason ${reason.message}`);
});
.as-console-wrapper {
max-height: 100% !important;
}
运行几次,以便您同时看到完成和拒绝(每次运行有 50/50 的机会)。除了主线程之外,该代码中的任何内容都不会在任何地方运行,只是通过 await
,example
中的逻辑可以等待一个 promise 来解决。 delay
的 promise 让我们观察计时器的完成,然后 example
await
在继续其逻辑之前完成。
关键是:
- Promises 不会使任何事情异步¹
- Promises 和
async
函数不会将任何东西移出主线程 async
函数总是返回 promisesasync
函数中的代码同步运行,直到第一个await
或return
- 来自
async
函数的 promise 通过函数的返回值实现,或者通过函数中发生的任何错误被拒绝
¹ 好的,有一个警告:如果您使用 .then
或 .catch
(或 .finally
)连接一个对 promise 的回调,该回调将始终被异步调用,即使 promise 已经已解决。
关于javascript - 异步函数 javascript 没有在后台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67354276/