gpt4 book ai didi

javascript - 为nodejs中的一系列 promise 添加延迟或 sleep

转载 作者:行者123 更新时间:2023-11-30 07:53:13 25 4
gpt4 key购买 nike

<分区>

我有一个一直在努力解决的 promise 链问题。我调用了一个外部 api,该 api 返回我需要处理并摄取到 mongo 数据库中的数据。我在 express 中使用 nodejs 和 mongodb。无论如何,对 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);
});
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com