Home > front end >  Node Js: How to send async request in batches
Node Js: How to send async request in batches

Time:09-26

Hope your all are doing fine.

I'm building a nodeJs script in which I want to call async requests in batches for example, I have an array of phone numbers like this some are correct numbers and some are incorrect numbers.

const chunks = [[" 1-321341321", "1-3213213213"], [" 1-3213321321"," 1-3213413213241"]]

and I am passing each array of items in a POST request but the API has certain criteria it only accepts a phone number that has ' ' in the start so if any batch contains a phone number that does not have ' ' it will throw an error.

try {
 chunks.forEach(async (item) => {
   await axios.post('https://example.com/v1', { to: item.map((pn) => {
                return {
                    phone_number: pn.toString().trim()
                }
            })})
})
} catch(e) {
    console.log(e)
}

It's working correctly but If the first batch request failed due to any reason (eg: bad phone number) it's throwing an error and stops the loop. what I want to do is that if any error occurs on any batch request it should move on to the next batch. A failed request on the first iteration should not block the next request on the iteration.

CodePudding user response:

try this

chunks.forEach((item) => {
  try {
    await axios.post('https://example.com/v1', {
      to: item.map((pn) => {
        return {
          phone_number: pn.toString().trim()
        }
      })
    })
  } catch (e) {
    console.error(e)
  }
})

CodePudding user response:

You could make the POST requests simultaneously with the help of Promise.all().

I think the following code should work:

Promise.all(chunks.map((item) => {
  return axios.post('https://example.com/v1', {
    to: item.map((pn) => {
      return { phone_number: pn.toString().trim() }
    })
  })
})).then((results) => {
  // ....
})

There is a slightly similar little example in the axios documentation.

  • Related