异步函数javascript没有在后台运行?

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!在那时

但是 async 函数的行为是同步的,不会让 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功能(或承诺)可以让任何东西在后台运行。他们不会创建新线程或类似的东西。

一个async函数在第一个await或之前是同步的return。由于您的函数没有任何awaitreturn,因此它是完全同步的。

承诺的目的是观察已经异步的东西的完成,比如浏览器通过 HTTP 加载东西,或者一个计时器。async函数的目的是使用 Promise 的语法,让我们可以编写代码的逻辑流,而不是编写回调函数。它们都不会使任何事情异步,也不会将事情移动到不同的线程。

如果你想在后台运行一些东西,你可以创建一个工作线程并通过消息在它和主线程之间交换信息。在浏览器上它是web workers。在 Node.js 中,它是工作线程模块。

在您的问题和对答案的评论中,您谈到了async函数似乎如何等待异步任务完成。事实上,函数的逻辑确实如此。但这确实是使用 promise 的语法糖(真的,非常好的语法糖,恕我直言)。我们来看一个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可以等待承诺解决。承诺 fromdelay让我们观察计时器的完成,然后example await在继续其逻辑之前完成该完成。

关键是:

  • 承诺不会使任何事情异步¹
  • Promise 和async函数不会从主线程移走任何东西
  • async 函数总是返回承诺
  • async函数中的代码同步运行,直到第一个awaitreturn
  • 从承诺async函数获取与函数的返回值完成,或发生在函数的任何错误而被拒绝

¹ 好的,有一个警告:如果您使用.thenor .catch(或.finally) 将回调连接到承诺,则该回调将始终被异步调用,即使承诺已经解决。


以上是异步函数javascript没有在后台运行?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>