我有一个使用请求模块的 rest 调用方法,它是 restRequest()
返回响应作为异步方法的 promise ,我必须在获得每个结果后使用不同的参数递归调用此方法并将该结果传递给相同的方法。
示例代码:
restRequest(url, "POST").then(function(response) {
restRequest(secondUrl, 'GET', response).then(function(response2) {
}):
});
这行得通吗,或者有什么其他办法可以解决这个问题。
最佳答案
我会使用 async这个库
特别是 waterfall
哪个会像
async.waterfall([
function firstRequest(callback) {
restRequest(url, "POST").then(function(response) {
callback(null, response);
});
},
function secondRequest (data, callback) {
restRequest(secondUrl, 'GET', data).then(function(response2) {
callback();
});
}
], function (err, result) {
// Handle err or result
});
抱歉格式化我在移动设备上。
您可以从上面的链接中了解 async.waterfall 的工作原理。
你的方法可行,但取决于你有多少请求,你最终可能会陷入相当深的回调 hell
但是因为你使用的是 promise ,你可以像这样返回你的 promise 链
restRequest(url, "POST")
.then(function(resp) {
return restRequest(secondUrl, "GET", resp);
})
.then(function(resp) {
return restRequest(thirdUrl, "GET", resp);
});
.then(function(resp) {
// do whatever keep the chain going or whatever
})
.catch(function(error) {
// if any of the promises error it will immediately call here.
});
有了 promises,您可以从 .then
中返回一个新的 promise
并保持链条无限运行。
我只是偏向于异步,因为我认为如果使用得当,它确实可以提高可读性。
关于javascript - 如何使用不同的参数递归调用异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35692861/