我正在尝试将一系列GET请求链接在一起。它们是一系列API调用,它们依赖于先前调用中的数据。我对Promise的理解是,我应该能够制作一条扁平的.then()链,但是当我尝试执行此操作时,我的function / console.logs没有按正确的顺序执行,因此我现在的金字塔越来越大的厄运:
var request = require('request');
var deferredGet = Q.nfbind(request);
deferredGet(*params*)
.then(function(response){
// process data from body and add it to the userAccount object which I am modifying.
return userAccount;
})
.then(function(userAccount){
deferredGet(*params*)
.then(function(response){
//process data from body and add to userAccount
return userAccount;
})
.then(function..... // There's a total of 7 API calls I need to chain, and it's already getting unwieldy.
我知道您应该兑现承诺,例如也许我应该兑现,deferredGet
但是当我尝试这样做时,我什么也没兑现。同样,传递给第一个参数then
是响应,而不是承诺。所以我不知道从这里去哪里,但我觉得我做错了。
提前致谢!
你是正确的,你应该回来deferredGet
。但是,意识到返回的仍然是一个承诺。因此,您之后应该保持链接链接.then
。
var request = require('request');
var deferredGet = Q.nfbind(request);
deferredGet(*params*)
.then(function(response){
// process data from body and add it to the userAccount object which I am modifying.
return userAccount;
})
.then(function(userAccount){
return deferredGet(*params*);
})
.then(function(response){
// response should be the resolved value of the promise returned in the handler above.
return userAccount;
})
.then(function (userAccount) {
//...
});
当您从then
处理程序中返回承诺时,Q将使其成为链的一部分。如果您从处理程序返回原始值,则Q会做出隐含的承诺,就像userAccount
在第一个处理程序中看到的那样,该承诺将立即立即使用该原始值进行解析。
看看我为您整理的这个工作示例:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句