【发布时间】:2018-05-22 01:00:20
【问题描述】:
我一直在努力解决一个承诺链问题。我调用了一个外部 api,它返回我需要处理和摄取到 mongo 数据库中的数据。我正在使用 nodejs 和 mongodb 和 express。无论如何,对 api 的调用工作正常,问题是我一次制作了大量的它们。我想放慢他们的速度,就像为一组打电话一样。等一下。为下一组打出所有电话。如果这是已知数量的集合,我会承诺将它们链接起来。我不知道有多少套,所以我正在循环播放它们。我认为关闭是问题,但无法解决。继续示例代码!
function readApi(carFactory){
var promise = new Promise(function(resolve, reject) {
// call out to api, get set of car data from factory1
console.log(carFactory);
if (true) {
console.log('resolved');
resolve("Stuff worked!"+carFactory);
}
else {
reject(Error("It broke"));
}
});
return promise;
}
function manager(){
//singular call
readApi("this is a singular test").then(returnedThing=>{
console.log(returnedThing); //Stuff worked! this is a singular test
});
let dynamicList = ["carFactory1", "carFactory2","carFactory3","carFactory..N"];
let readApiAction = [];
dynamicList.forEach(carIter=>{
readApiAction.push(readApi(carIter));
});
//ok so now I got an array of promise objects.
//I want to call the first one, wait 1 minute and then call the next one.
//originally I was calling promise.all, but there is no way to get at
//each promise to pause them out so this code is what I am looking to fix
let results= Promise.all(readApiAction);
results.then(data=>{
data.forEach(resolvedData=>{
console.log(resolvedData); //Stuff worked carFactory1, etc...
});
});
//singular call with timeout, this does not work, each one called at the same time
let readApiActionTimeouts = [];
dynamicList.forEach(carIter=>{
setTimeout(callingTimeout(carIter), 6000);
});
}
//just a function to call the promise in a timeout
//this fails with this - TypeError: "callback" argument must be a function
function callingTimeout(carIter){
readApi(carIter).then(returnedThing=>{
console.log("timeout version"+returnedThing);
});
}
【问题讨论】:
-
在 SO 上有几十个类似类型的问题,关于在对外部服务器进行大量 API 调用时如何处理速率限制。
-
这并不是一个与 api 相关的真正限制问题,抱歉,我一定不清楚。我正在尝试调用一个 promise 函数,然后等待,然后再次调用同一个函数,N 次。
-
那么你已经把问题变得比需要的复杂了。只需搜索“测序承诺数组”。有数百个相关答案。
标签: javascript node.js callback promise async-await