1008JS Loops and async/await
I've been trying to get data from an API, a async call is used to parse the data. I've be naively iterating over the responses with forEach
, calling await
in the forEach function
, and wondering why it is not producing the result I expected, i.e. wait for the data to settle.
NG:
async function getData() {
output = ""
results.forEach(async (block) => {
var b = await abc.parse(block)
output += b
})
}
Solution
Use a standard for
or for..of
to loop over the list:
async function getData() {
output = ""
for (const block of results) {
var b = await abc.parse(block)
output += b
}
}