Sequential requests with request-promise
Asked Answered
M

1

6

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?

Magpie answered 28/1, 2016 at 3:15 Comment(0)
T
10

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
    // ...
});
Terylene answered 28/1, 2016 at 3:55 Comment(2)
This is good, but I'm having an issue where it seems like my second request is called twice, and then my third request is called four times. Why might that be?Swinson
Sorry, it was my mistake. Setting the simple option to false looks like it fixed the issue. It might have been because it was by passing my own error handling for requests that weren't 200.Swinson

© 2022 - 2024 — McMap. All rights reserved.