您可以在提供给Promise
的onFulfilled
函数中返回 a 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
// .....
});
这使您可以处理多个呼叫,而不会陷入嵌套的噩梦;-)
此外,如果您不关心哪个确切Promise
失败,这会使错误处理变得更加容易:
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
// ...
});