I am doing several fecth.
let var1 = []
let var2 = []
await dateArray?.map((day) => {
for (const o of myFirstList) {
for (const d of mySecondList) {
const resp = fetch(url-with-params)
.then((resp) => resp.json())
.then((data) => {
const f = manipulateResponse(data)
logger.info('1: manipulated data')
var1.push(f.data1)
var2.push(f.data2)
})
}
}
})
logger.info('2: return response')
let response = {
var1,
var2,
}
return response
The problem is the log return response
is being called first then manipulated data
.
How can I assure to run all fetch’s before the function return the complete result?
PS: I have done with then()
and await
.
2
Answers
To ensure all the fetch operations complete before returning the response, use
Promise.all
withawait
on an array of fetch promises. This will wait for all fetch operations to finish before proceedingThe issue you’re facing is due to the asynchronous nature of JavaScript and the fact that fetch returns a Promise. One way is to use
Promise.all
to wait for all the promises generated by the fetch requests to be resolved.Example: