2

The problem

I am using axios to post multiple request to an API, the order these request reach the API is important. Even though the requests are been sent in the correct order, they are been handled in the wrong order on the API layer (response is been sent back in the incorrect order).

e.g. i send request A and then B, but received the response B first and then A.

What i am doing currently

const requests = request.map(req => {

  return post<void>(url, params)
    .then(response => {
       console.log(`response sent`);
    })
    .catch(err => {
       console.log(`Response not sent`, err);
    });

});

await Promise.all(requests);
Michael Peyper
  • 6,814
  • 2
  • 27
  • 44
user3125462
  • 61
  • 1
  • 3
  • 8

2 Answers2

1

How about something like this:

const [first, ...others] = request

const makeRequest = ({ url, params }) => post<void>(url, params)
  .then(response => {
    console.log(`response sent`)
  })
  .catch(err => {
    console.log(`Response not sent`, err)
  })

const requests = others.reduce((promise, req) => {
  return promise.then(() => makeRequest(req))
}, makeRequest(first))

await requests

This will chain each request onto the previous request, if it was successful.

Note: I'm making the assumption that url and params are values on the requests as I can't see in your code where they are coming from.

Michael Peyper
  • 6,814
  • 2
  • 27
  • 44
0

you have to create strictly ordered array to solve your issue. refer Promise.all: Order of resolved values

ajit-jain
  • 206
  • 2
  • 6
  • how do you know if an array is strictly ordered? Secondly i don't think i've made myself clear. If i send request A first, then B, it is important I know A has been handled by the API before I send request B. – user3125462 Nov 25 '17 at 12:16
  • for example if i did, await post(ApiPaths, params) etc. This would ensure that the response has been received before posting the next request. – user3125462 Nov 25 '17 at 12:52