How to execute a synchronous request in a looping

Asked

Viewed 357 times

2

In the example below

let arr = [
  { 3 : 'teste' },
  { 5 : 'teste' },
  { 1 : 'teste' },
  { 2 : 'teste' },
  { 0 : 'teste' },
  { 4 : 'teste' }
];

arr = arr.sort( ( a , b ) => { return Object.keys(b)[0] - Object.keys(a)[0] } )

console.log( arr )

/*
[ { '5': 'teste' },
  { '4': 'teste' },
  { '3': 'teste' },
  { '2': 'teste' },
  { '1': 'teste' },
  { '0': 'teste' } ]
*/

arr.forEach( ( el, key ) => {

  fetch( this.url + el[ Object.keys(el)[0] ], {
      method: 'GET',
      headers: {
          Accept: 'application/json'
      }
  }).then((response) => {
      return response.json();
  }).then((result) => {

  ...

} )

I order an array in descending order based on key of every object within it, for when I execute the looping, need to execute the request from the largest to the smallest.

The problem is that the fetch is asynchronous ie, this order will not work because it executes the requests in parallel, and which receive the result will first enter the then or in the catch

I need the forEach wait for the request to finish to go to the next item, it is possible?

1 answer

2


You can use the method Promise.all() to execute all asynchronous requests and, when all results are received, work with them in the same order in which they were called.

Promise.all([req_1, req_2, req.3]).then(reqs => {
    console.log(reqs) // [result_1, result_2, result_3]
})

Your code would look like this:

let arr = [
  { 3 : 'teste' },
  { 5 : 'teste' },
  { 1 : 'teste' },
  { 2 : 'teste' },
  { 0 : 'teste' },
  { 4 : 'teste' }
];

arr = arr.sort(( a , b ) => Object.keys(b)[0] - Object.keys(a)[0])

const URL = "https://httpbin.org/anything"
let requests = arr.map(obj => fetch(URL, {
  method: "POST",
  body: JSON.stringify(obj)
}))

Promise.all(requests)
  .then(responses => {
    responses.forEach(response => {
      response.json().then(json => console.log(json.data))
    })
  })

  • Thanks for the @fernandosavio reply, the solution almost solved my problem, in promisse.all are entering many results, and when it loops sometimes they enter the then out order, which makes sense because even if the then is not expecting a request, still there are processing delays I believe, what ends up breaking the cycle, you would know how to solve it?

  • This only happens in Mozilla actually

  • Strange, in the documentation of MSN specifies that the array passed to the function is in the order of the Promises array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.