亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Vue.js 異步/等待,然后函數未執行

Vue.js 異步/等待,然后函數未執行

呼喚遠方 2021-07-13 13:05:56
我正在嘗試在 for of 循環中將 async/await 與 axios.then() 一起使用。該函數無法運行甚至嘗試 axios 調用。我有一種感覺,使用 then() 函數是問題的一部分。在繼續處理下一個數組項之前,我需要 for 循環等待 then() 函數運行。任何想法如何更改我的代碼以使 axios.then() 函數異步運行?accounts = [{a},,{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 關注
  • 506 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號