skip to Main Content

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


  1. Chosen as BEST ANSWER

    To be sure, I also tested this way:

    const fetchMethod = (item)=>{
      return new Promise((resolve, reject)=>{
        setTimeout(()=>{
           resolve (fetch(`https://jsonplaceholder.typicode.com/todos/${item}`))
        }, item === 1 ? 5000 : 1000);
      })
    }
    
    async function example() {
      for (item of [1, 2, 3]) {
        let res = await fetchMethod(item)
        let res2 = await res.json()
        console.log(res2);
      }
    }
    
    example();


  2. use await flag. so await fetch(…) should do it

    async function example() {
      for (item of [1, 2, 3]) {
        let res = await fetch(`http://test.com/users/${item}`);
        console.log(res.id); // I want the next request, to be send after received this reponse
      }
    }
    Login or Signup to reply.
  3. Instead of using .then(), you should use await, which works inside for, while and do..while loops (also, you should probably wrap the fetch calls in a try...catch):

    function fakeFetch(url) {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ id: url })
        }, 1000)
      })
    }
    
    async function fetchItems() {
      for (let item of [1,2,3]){
        console.log(`Fetching ${ item }...`)
        
        try {
          const res = await fakeFetch(`http://test.com/users/${ item }`)
    
          console.log(res.id)
        } catch (err) {
          console.log(`Item ${ item } error:`, err)
        }
      }
    }
    
    fetchItems()

    Note this won’t work for Array methods that require a callback such as forEach, map, reduce or filter.

    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():

    function fakeFetch(url) {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ id: url })
        }, 1000)
      })
    }
    
    async function fetchItems() {
      const promises = [1,2,3].map((item) => {
        console.log(`Fetching ${ item }...`)
        
        return fakeFetch(`http://test.com/users/${ item }`)  
      })
      
      const items = await Promise.allSettled(promises)
      
      console.log(items)
    }
    
    fetchItems()
    Login or Signup to reply.
  4. 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 using async/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:

    async function fetchUsersSequentially() {
      for (const item of [1, 2, 3]) {
        try {
          const response = await fetch(`http://test.com/users/${item}`);
          const data = await response.json();
          console.log(data.id);
        } catch (error) {
          console.error(`Error fetching user ${item}:`, error);
        }
      }
    }
    
    fetchUsersSequentially();
    

    In the above code, we define an async function fetchUsersSequentially(). Inside the loop, we use await to wait for the response to be received and then parse the response using response.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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search