Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequential requests with request-promise

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?

like image 908
Joshua Gilman Avatar asked Jan 28 '16 03:01

Joshua Gilman


People also ask

Is Promise all multithreaded?

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.

How do you call multiple promises?

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.

Does Promise all throw error?

all() does not get rejected when one of the array elements (passed as an argument to Promise. all()) throws an error.


1 Answers

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
    // ...
});
like image 100
forrert Avatar answered Sep 28 '22 18:09

forrert