请求承诺的顺序请求
有没有一个嵌套的方式来实现以下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 // ..... }); });
每个请求都取决于最后的结果,所以它们需要是顺序的。 然而,我的一些逻辑需要多达五个连续的请求,并导致相当嵌套的噩梦。
我是否在谈论这个错误?
您可以在Promise
提供的onFulfilled
函数中返回一个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
失败,这使得error handling更容易一些:
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 // ... });