【问题标题】:Event loop flow with Async/Await带有 Async/Await 的事件循环流
【发布时间】:2018-03-22 02:08:24
【问题描述】:

我一直在尝试使用 Javascript 中的 Async/Await 命令,并注意到一些令我感到困惑的事情。

当我在调试模式下在 Visual Studio Code 中运行以下代码时,在我到达第一行“等待”代码后,它会跳转到函数的末尾,然后按顺序继续执行其余代码,包括其他代码等待'行。为什么是这样?

const axios = require("axios");
const apiURL = 'https://jsonplaceholder.typicode.com/posts/1'

async function multipleRequestsAsync() {
  try {
    console.log("starting...")
    const response1 = await axios.get(apiURL);
    console.log(response1.data);
    const response2 = await axios.get(apiURL);
    console.log(response2.data);
    const response3 = await axios.get(apiURL);
    console.log(response3.data);
  } catch (error) {
    console.error(error);
  }
}

multipleRequestsAsync();

这里是code in jsfiddle

这是我正在谈论的内容的动画 gif。

【问题讨论】:

  • 猜测,这表明该函数此时返回了一个承诺
  • 你在使用转译器吗?
  • @Bergi - 不,我没有使用转译器。除了 Visual Studio 代码之外,我没有其他方法来调试它,看看它是否只是 Visual Studio 代码。
  • @Jaromanda X - 也许,虽然我会认为要么所有带有'await'语句的调用在继续之前都首先落在函数的末尾,或者它们都没有这样做......不仅仅是第一个“等待”声明。
  • 不,这没有意义,一个函数只能返回一个值——在异步函数的情况下,它会在第一个等待被调用的地方返回一个承诺

标签: javascript debugging async-await visual-studio-code


【解决方案1】:

它可能表示函数返回承诺的点。如果您在调用async function 之后包含一些其他代码,那么在事件循环的未来轮次中,在await 之后继续执行之前将逐步执行这些代码。考虑

async function multipleRequestsAsync() {
  try {
    console.log("starting...");                // 3
    const response1 = await axios.get(apiURL); // 4
    console.log("done");                       // 7
  } catch (error) {
    console.error(error);
  }
}                                              // 5

console.log("before start");                   // 1
const promise = multipleRequestsAsync();       // 2
console.log("continuing...");                  // 6

你会得到输出

before start
starting...
continuing
// later:
done

函数结束处的断点 (5) 将发生在离开函数 await (4) 和调用之后的语句 (6) 之间。

【讨论】:

  • 那么你是说如果在 (4)/(7) 之后有重复的 (4) 和 (7) 行(就像在我的示例中一样),你不会看到它转到 ( 5)在第二次重复(4)之后......就在第一次等待电话之后?如果是这样,为什么会这样?
  • @ArthurFrankel 是的,这就是你的 gif 显示的内容,对吧?该函数只返回一次承诺。
猜你喜欢
  • 2021-08-13
  • 2019-01-06
  • 2020-05-30
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 2016-02-04
  • 2019-07-16
  • 1970-01-01
相关资源
最近更新 更多