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)
}
}
}

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)
})
}
})();
},

TA貢獻1794條經驗 獲得超8個贊
該問題最終是由 Vue 前端編譯我的應用程序引起的,該應用程序目前不支持開箱即用的 async/await。通過遵循此處發布的堆棧溢出解決方案解決。請注意,代碼現在按預期運行。外賣:
使用簡單的測試來確認問題不是代碼
如果以上不起作用,請檢查 webpack、babel 或其他編譯器配置
函數無法運行時缺少錯誤可能表示編譯錯誤。檢查配置。
添加回答
舉報