繁体   English   中英

Vue.js异步/等待,然后函数不执行

[英]Vue.js async/await with then function not executing

我试图在for循环中将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和其他编译器配置

通常,将promise接口(即.then() )与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)
    }
  }
}

感谢Dacre Denny的快速帮助。 他的测试代码帮助我确定问题出在代码之外。

该问题最终是由于Vue前端编译了我的应用程序引起的,该应用程序目前不支持开箱即用的异步/等待功能。 通过遵循此处发布的堆栈溢出解决方案来解决。 请注意,该代码现在可以按预期运行。 Takeways:

  1. 使用简单的测试来确认问题,而不是代码
  2. 如果上述方法不起作用,请检查webpack,babel或其他编译器配置
  3. 如果函数无法运行,则缺少错误可能表示编译错误。 检查配置。
  async get_user_data(accounts) {
        // For of loop
        (async() => {
            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)
                    })
            }
        })();
    },

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM