javascript - 在异步函数中调用同步函数

标签 javascript node.js asynchronous

我无法理解异步函数在 JavaScript 中的工作原理。我们来看下面的代码:

async () => {
      console.log(1);
      setTimeout(() => console.log(2)
        , 2000)
      console.log(3);
}

我希望在执行进一步的代码之前,在异步内部调用同步函数应该阻塞线程。所以我希望得到 1 -> 2 -> 3 而不是我得到 1 -> 3 -> 2。找不到发生这种情况的原因以及如何阻止线程接收输出 1 -> 2 -> 3 的解释。 我正在使用 Node 12 和无服务器框架。

最佳答案

async 本身不会等到 setTimeout 的执行按您的预期完成。正如您可以从文档中阅读的那样 - 在此处查找 async :

An async function can contain an await expression that pauses the execution of the async function to wait for the passed Promise's resolution, then resumes the async function's execution and evaluates as the resolved value.

刚刚构建了一个快速示例,以了解 asyncawait 解决方案之间的区别,并仅使用 setTimeout (如示例中所示)。

考虑以下示例:

const getPromise = async () => {
  return new Promise((resolve) => {
    setTimeout(resolve, 3000);
  });
}

const run = async () => {
  console.log('run started');
  setTimeout(() => console.log('setTimeout finised'), 2000);
  console.log('setTimeout started');
  const promise = await getPromise();
  console.log('Promise resolved');
  console.log('run finished');
}

run();

步骤说明:

  1. 记录函数run执行开始的情况
  2. 将一个事件附加到 setTimeout,该事件将在大约 2 秒内完成
  3. 登录到 setTimeout 启动的控制台
  4. 使用 getPromise 函数创建 Promise,并使用 await 关键字等待 resolve
  5. 大约 2 秒内 setTimeout 记录它已完成
  6. Promise 后大约 3 秒内调用 resolve 函数
  7. run 函数在 resolve 和日志记录后完成执行。

我希望能帮助您理解这部分代码。

关于javascript - 在异步函数中调用同步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59694469/

相关文章:

javascript - 初学者 JavaScript 变量

javascript - Safari getUserMedia() 未处理的 promise 拒绝

javascript - Node + socket.io 与 nginx 正确设置

javascript - 使用Node.js同步下载N个远程文件

c# - 如果我知道 API 在某个时候执行 I/O,我是否应该异步调用 brownfield API?

javascript - 始终将选定的数据保留在新数组中(React Native)

javascript - 登录后如何将用户发送到另一个页面(node js)

javascript - 如何从同一个 Express Controller 脚本加载不同的 html 页面?

c++ - std::async 的非阻塞调用:这个版本有多危险?

javascript - 在 Canvas 中画圈的一侧边框