這裏是Node.js的新增內容。我正在尋找從另一個函數中調用N個異步API調用的正確方法,並將它們的結果組合到更下游。在我的情況下,N會相當小,阻止執行不會太差。結合多個Node.js API調用的結果
在同步執行中,combine()的實現應該可以工作。
如果我只需要一個API調用的結果,那麼在提供給callAPI()的回調函數中實現以下邏輯將很簡單。當我在執行foo之前需要結合所有結果(總數,[... args])時,我偶然發現。
我看着async.whilst
,但無法讓它工作。我懷疑這是否符合我的需求。我也看過Promises
這似乎是正確的領先優勢,但在爬進那個海綿狀的兔洞之前得到保證是件好事。是不是Promises
是正確的方式,哪個模塊是在Node.js
項目中使用的標準?
var http = require('http');
function callAPI(id) {
var options = {
host: 'example.com',
path: '/q/result/'.concat(id)
}
var req = http.get(options, (res) => {
var body = [];
res.on('data', (chunk) => {
body.push(chunk);
}).on('end',() => {
body = Buffer.concat(body).toString();
return body;
}).on('error', (err) => {
console.error(err);
});
});
}
function combine(inputs) {
var total = 0;
for (i=0; i < inputs.length; i++) {
total += callAPI(inputs[i]['id']);
};
console.log(total);
// call some function, foo(total, [...args])
}
編輯1:
我試圖按照以下samanime的答案,修改API調用返回的承諾。參見:
function callAPI(id) {
return Promise((resolve, reject) => {
var options = {
host: 'example.com',
path: '/q/result/'.concat(id)
}
var req = http.get(options, (res) => {
var body = [];
res.on('data', (chunk) => {
body.push(chunk);
}).on('end',() => {
body = Buffer.concat(body).toString();
resolve(body);
}).on('error', (err) => {
reject(err);
});
});
});
}
function combine(inputs) {
var combined = [];
for (i=0; i < inputs.length; i++) {
total += callAPI(inputs[i]['id']);
.then(result => {
combined.push(result);
});
};
var total = combined.reduce((a, b) => a + b, 0);
console.log(total);
// call some function, foo(total, [...args])
}
這似乎讓我在那裏一半。如果我在then()
塊內,我可以看到用API調用的結果構建的列表。但是,我仍然無法在for
循環的「結尾」訪問完整的combined
。在建立完整列表後,我可以附加一個回調函數來運行嗎?有沒有更好的辦法?
編輯2(我的解決方案 - 每帕特里克·羅伯茨建議)
function callAPI(id) {
return Promise((resolve, reject) => {
var options = {
host: 'example.com',
path: '/q/result/'.concat(id)
}
var req = http.get(options, (res) => {
var body = [];
res.on('data', (chunk) => {
body.push(chunk);
}).on('end',() => {
body = parseInt(Buffer.concat(body));
resolve(body);
}).on('error', (err) => {
reject(err);
});
});
});
}
function combine(inputs) {
var combined = [];
Promise.all(inputs.map(input => callAPI(input.id)))
.then((combined) => {
var total = combined.reduce((a, b) => a + b, 0);
// foo(total, [...args])
});
};
試試這個https://開頭計算器。com/questions/44636542/loop-through-asynchronous-request/44636736#44636736它正是你在找什麼。 –