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);
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.