Reputation: 585
I'm attempting to use async/await with axios.then() within a for of loop. The function fails to run or even attempt the axios call. I have a feeling using the then() function is part of the problem.
I need the for loop to wait until the then() function has run before continuing on to the next array item. Any ideas how I can alter my code to get the axios.then() functions to run asynchronously?
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)
})
}
}
UPDATE:
Issue was ultimately being caused by the Vue frontend compiling my application. Resolved by following the stack overflow solution posted here. Note, that the code now functions as expected. The solution offered by Dacre Denny helped me decide the issue must be located somewhere else as his should have worked but did not until the problem with Vue was solved. Takeaways:
Upvotes: 2
Views: 5627
Reputation: 72
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)
})
}
})();
},
Upvotes: 0
Reputation: 585
Thanks to Dacre Denny for the quick help. His test code helped me determine the problem was not with the code.
The Issue was ultimately being caused by the Vue frontend compiling my application which does not at this date support async/await out of the box. Resolved by following the stack overflow solution posted here. Note, that the code now functions as expected. Takeways:
Upvotes: 0
Reputation: 30390
In general, it is considered an anti-pattern to mix the promise interface (ie .then()
) with await/async
semantics.
Seeing that the get_user_data
function is defined async
, consider a revised implementation based on a try/catch
block for clearer program flow and greater predictability in the asynchronous behaviour of your loop:
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)
}
}
}
Upvotes: 2