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?

1 Answer 1

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 // ... }); 
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.