0

How to call HTTP requests asynchronously in Node JS. I have 3 major challenges as below.

  • Requires to call asynchronously.
  • Request URL is dynamic.
  • Avoid using loops.

The below method is used to call single endpoint.

const options = {
    method: 'POST',
    uri: "http://api.example.com"
}

const response = await request(options);

RequestPromise NPM


In order to call asynchronously, I have used parallel-http-request as below.

request.add({
    url:'https://jsonplaceholder.typicode.com/posts/1', 
    method:'post',
})
.add({
    url:'https://jsonplaceholder.typicode.com/posts/2', 
    method:'post'
})
.add({
    url:'https://jsonplaceholder.typicode.com/posts/3', 
    method:'post'
});

Both the above methods support static number of API requests which cannot be dynamically handled.

E.g. When using parallel-http-request it needs to be add .add({ keyword in the JS code and this will not support dynamic URL parameters.

Is there any other way to achieve this task? Thanks in advance.

Harsha W
  • 3,162
  • 5
  • 43
  • 77

1 Answers1

0

Use Promise.all and wrap all the request promise in an array.

 await Promise.all([
  request({
      url:'https://jsonplaceholder.typicode.com/posts/1', 
      method:'post',
  }),
  request({
      url:'https://jsonplaceholder.typicode.com/posts/2', 
      method:'post'
  }),
  request({
    url:'https://jsonplaceholder.typicode.com/posts/3', 
    method:'post'
  })
]);

Also, since is a possibility of promise getting reject. wrapping a try-catch is a must.

try {
  await Promise.all([
    request({
        url:'https://jsonplaceholder.typicode.com/posts/1', 
        method:'post',
    }),
    request({
        url:'https://jsonplaceholder.typicode.com/posts/2', 
        method:'post'
    }),
    request({
      url:'https://jsonplaceholder.typicode.com/posts/3', 
      method:'post'
    })
  ]);
} catch (e) { 
  // handle if any one of the request is failed
}
prasana kannan
  • 646
  • 6
  • 12