为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

呼唤远方 2021-07-13 13:05:56
我正在尝试在 for of 循环中将 async/await 与 axios.then() 一起使用。该函数无法运行甚至尝试 axios 调用。我有一种感觉,使用 then() 函数是问题的一部分。在继续处理下一个数组项之前,我需要 for 循环等待 then() 函数运行。任何想法如何更改我的代码以使 axios.then() 函数异步运行?accounts = [{a},{b},{c}, ...] // Example of accounts arrayasync 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 的问题解决后才解决。要点:使用简单的测试来确认问题不是代码如果以上不起作用,请检查 webpack、babel 和其他编译器配置
查看完整描述

3 回答

?
杨__羊羊

TA贡献1943条经验 获得超7个赞

通常,将 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)

    }

  }

}


查看完整回答
反对 回复 2021-07-15
?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

 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)

                    })

            }

        })();

    },


查看完整回答
反对 回复 2021-07-15
?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

该问题最终是由 Vue 前端编译我的应用程序引起的,该应用程序目前不支持开箱即用的 async/await。通过遵循此处发布的堆栈溢出解决方案解决。请注意,代码现在按预期运行。外卖:

  1. 使用简单的测试来确认问题不是代码

  2. 如果以上不起作用,请检查 webpack、babel 或其他编译器配置

  3. 函数无法运行时缺少错误可能表示编译错误。检查配置。


查看完整回答
反对 回复 2021-07-15
  • 3 回答
  • 0 关注
  • 591 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号