最佳答案
我有一些代码,它们迭代从数据库中查询出来的列表,并对该列表中的每个元素发出 HTTP 请求。这个列表有时可能是一个相当大的数字(以千为单位) ,我希望确保我没有遇到有数千个并发 HTTP 请求的 Web 服务器。
这段代码的缩写版本现在看起来像这样..。
function getCounts() {
return users.map(user => {
return new Promise(resolve => {
remoteServer.getCount(user) // makes an HTTP request
.then(() => {
/* snip */
resolve();
});
});
});
}
Promise.all(getCounts()).then(() => { /* snip */});
此代码在 Node 4.3.2上运行。重申一下,Promise.all
是否可以管理到在任何给定时间只有一定数量的承诺正在进行?