javascript - 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 的问题解决后才解决。要点:
- 使用简单的测试来确认问题而不是代码
- 如果上述方法不起作用,请检查 webpack、babel 和其他编译器配置
解决方案
.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)
}
}
}
推荐阅读
- objective-c - AFNetworking:访问块外的变量是否安全?
- node.js - 在没有指定密码的情况下在windows上运行的节点中对mongodb进行kerberos身份验证?
- vba - VBA宏触发太频繁
- reactjs - Redux 即时更新,但 react 组件有异步延迟
- ruby-on-rails - Rails debounce延迟作业后台任务?删除重复项
- mysql - node.js MySQL 连接未建立 - 仅在使用 XAMPP 时
- sql - 在 SSMS 2014 结果中添加双引号(需要来自原始帖子的响应)
- angularjs - angularjs - 在没有路由/ng-view 的情况下实现路由的解析功能
- excel - 在 Outlook 中的子内调用子 - 范围类的自动筛选方法失败
- macos - 为什么 docker 会消耗这么多 VIRT 内存?