How can I write a loop and send a request to the server so that the next request is performed after receiving the response in the previous request?
I want the requests to be sent in order and the results to be displayed in order:
for (item of [1,2,3]){
fetch(`http://test.com/users/${item}`).then((res)=>{
console.log(res.id) // I want the next request, to be send after received this reponse
})
}
4
Answers
To be sure, I also tested this way:
use await flag. so await fetch(…) should do it
Instead of using
.then()
, you should useawait
, which works insidefor
,while
anddo..while
loops (also, you should probably wrap thefetch
calls in atry...catch
):Note this won’t work for Array methods that require a callback such as
forEach
,map
,reduce
orfilter
.The drawback of this approach is that it takes longer than resolving the promises (requests) in parallel, as you wait for one to resolve before making the next request. Instead, you might want to consider using
Promise.allSettled()
:To send requests in order and wait for the response of each request before sending the next one, you can use the
async/await
syntax. By usingasync/await
, you can make asynchronous code look more synchronous, and it allows you to pause the execution of a function until an asynchronous operation is complete.Here’s how you can modify your code to achieve this:
In the above code, we define an
async
functionfetchUsersSequentially()
. Inside the loop, we useawait
to wait for the response to be received and then parse the response usingresponse.json()
. This way, the next request will be sent only after the previous request has been processed completely.Remember that when using
async/await
, it’s important to handle errors using a try-catch block. If any request fails, the catch block will handle the error, and the loop will continue to the next iteration.Now, when you call
fetchUsersSequentially()
, the requests will be sent in order, and the responses will be logged in order.