Javascript Vue.js异步/wait with then函数未执行
我正在尝试在for-of循环中对axios.then()使用async/await。该函数无法运行,甚至无法尝试axios调用。我觉得使用then()函数是问题的一部分 我需要for循环等到then()函数运行后再继续下一个数组项。你知道如何修改代码以使axios.then()函数异步运行吗Javascript Vue.js异步/wait with then函数未执行,javascript,promise,vuejs2,async-await,axios,Javascript,Promise,Vuejs2,Async Await,Axios,我正在尝试在for-of循环中对axios.then()使用async/await。该函数无法运行,甚至无法尝试axios调用。我觉得使用then()函数是问题的一部分 我需要for循环等到then()函数运行后再继续下一个数组项。你知道如何修改代码以使axios.then()函数异步运行吗 accounts = [{a},{b},{c}, ...] // Example of accounts array async function get_user_data (accounts) {
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的问题得到解决后才生效。外卖:
通常,将promise接口(即
.then()
)与await/async
语义混合在一起被认为是一种反模式
<> > <代码> > GeGuSuelyDATA < /Case>函数定义为“代码> AsYNC/<代码>,考虑基于<代码> Test/Ccatch < /Cord>块的修改实现,以实现更清晰的程序流程和更大的可预测性:
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前端编译我的应用程序引起的,该应用程序目前不支持异步/等待开箱即用。按照堆栈溢出解决方案解决。请注意,代码现在的功能与预期相同。途径:
我认为在for循环内部发送http请求不是一个好主意。此
for
循环的可能副本将在继续之前等待.then()
运行。如果您认为不是,那么可能是因为您在.then()
处理程序中执行的任何异步操作都没有返回承诺,因此它可以链接到链中。向我们展示.then()
处理程序中的内容的代码,我们更有可能为您提供帮助。仅供参考,您不需要在此处给出问题的答案。你把答案放在答案里,把问题放在问题里。所以,既然你已经发布了自己的答案(这在这里是允许的),那么你应该从问题中删除答案内容。它不属于那里。经过一段时间后,您也可以“接受”您的答案。如果问题不在问题中,则不会标记导致问题的代理(Vue.js),解决方案也会出现在另一篇文章中,请更新标题并将此问题标记为重复问题,或将其删除。这本身不会,解决OP遇到的任何问题,因为OP的代码已经在等待.then()
处理程序运行。人们可能会争论使用await
和.then()
的“风格”,但这并不会导致OP出现任何问题。
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)
})
}
})();
},