[英]Using Q Promises to chain GET requests in node.js
我正在嘗試將一系列GET請求鏈接在一起。 它們是一系列API調用,依賴於先前調用的數據。 我對承諾的理解是我應該能夠創建一個扁平的.then()鏈,但是當我試圖這樣做時,我的函數/ 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
處理程序中返回一個promise時,Q將使它成為鏈的一部分。 如果從處理程序返回原始值,Q將生成隱含的承諾,只需立即解析該原始值,就像您在第一個處理程序中看到userAccount
。
看看我為你准備的這個工作示例 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.