首页 > 解决方案 > Vue.js async/await with then 函数未执行

问题描述

我正在尝试在 for of 循环中将 async/await 与 axios.then() 一起使用。该函数无法运行,甚至无法尝试 axios 调用。我感觉使用 then() 函数是问题的一部分。

我需要 for 循环等到 then() 函数运行后再继续下一个数组项。有什么想法可以更改我的代码以使 axios.then() 函数异步运行吗?

accounts = [{a},{b},{c}, ...] // Example of accounts array

async function get_user_data (accounts) {
  // For of loop
  for (let [index, user] of accounts.entries()) {
    // Currently using await before axios call
    await axios.get(url, headers)
      .then(function(data) {
        console.log(data)
      })
      .catch(function(error) {
        console.log(error)
      })
  }
}

更新:

问题最终是由 Vue 前端编译我的应用程序引起的。按照此处发布的堆栈溢出解决方案解决。请注意,代码现在按预期运行。Dacre Denny 提供的解决方案帮助我确定问题必须位于其他地方,因为他应该可以解决问题,但直到 Vue 的问题解决后才解决。要点:

  1. 使用简单的测试来确认问题而不是代码
  2. 如果上述方法不起作用,请检查 webpack、babel 和其他编译器配置

标签: javascriptpromisevuejs2async-awaitaxios

解决方案


.then()通常,将 promise 接口(即)与await/async语义混合被认为是一种反模式。

看到get_user_data函数已定义async,请考虑基于try/catch块的修订实现,以获得更清晰的程序流程和更大的循环异步行为的可预测性:

async function get_user_data (accounts) {
  for (let [index, user] of accounts.entries()) {

    /* try/catch block allows async errors/exceptions to be caught
    without then need for a .catch() handler */
    try {    

        /* Using await, the response data can be obtained in this 
        way without the need for a .then() handler */
        const data = await axios.get(url, headers)
        console.log(data);
    }
    catch(error) {

        /* If an error occurs in the async axios request an exception
        is thrown and can be caught/handled here */
        console.log(error)
    }
  }
}

推荐阅读