Is there a less-nested way to achieve the following with request-promise
:
r = require('request-promise');
r(url1).then(function(resp1) {
// Process resp 1
r(url2 + 'some data from resp1').then(function(resp2) {
// Process resp 2
// .....
});
});
Each request is dependent on the result of the last, and so they need to be sequential. However, some of my logic requires up to five sequential requests and it causes quite the nested nightmare.
Am I going about this wrong?
Often Promise. all() is thought of as running in parallel, but this isn't the case. Parallel means that you do many things at the same time on multiple threads. However, Javascript is single threaded with one call stack and one memory heap.
In this approach, we will use Promise. all() method which takes all promises in a single array as its input. As a result, this method executes all the promises in itself and returns a new single promise in which the values of all the other promises are combined together.
all() does not get rejected when one of the array elements (passed as an argument to Promise. all()) throws an error.
You can return a Promise
in the onFulfilled
function provided to Promise.then
:
r = require('request-promise');
r(url1).then(function(resp1) {
// Process resp 1
return r(url2 + 'some data from resp1');
}).then(function(resp2) {
// resp2 is the resolved value from your second/inner promise
// Process resp 2
// .....
});
This lets you handle multiple calls without ending up in a nested nightmare ;-)
Additionally, this makes error handling a lot easier, if you don't care which exact Promise
failed:
r = require('request-promise');
r(url1).then(function(resp1) {
// Process resp 1
return r(url2 + 'some data from resp1');
}).then(function(resp2) {
// resp2 is the resolved value from your second/inner promise
// Process resp 2
// ...
return r(urlN + 'some data from resp2');
}).then(function(respN) {
// do something with final response
// ...
}).catch(function(err) {
// handle error from any unresolved promise in the above chain
// ...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With