6

是否有一种嵌套较少的方法来实现以下目标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
        // .....
    });
});

每个请求都依赖于最后一个请求的结果,因此它们需要是顺序的。然而,我的一些逻辑需要多达五个连续的请求,这导致了相当嵌套的噩梦。

我要解决这个问题了吗?

4

1 回答 1

10

您可以在提供给PromiseonFulfilled函数中返回 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
    // ...
});
于 2016-01-28T03:55:17.403 回答