gpt4 book ai didi

javascript - q.allSettled 有默认超时吗?

转载 作者:行者123 更新时间:2023-12-03 08:47:24 26 4
gpt4 key购买 nike

我正在开发一个 NodeJS 应用程序,它从不同的 API 获取大量信息。

在最大的抓取过程中,我的 promise 出现了一些问题。

我想我发起的请求太多而且速度太快......

 var promises = [];
list_consumptions.forEach(function (item)
{
item.consumptions.forEach(function (data)
{
promises.push(getDetails(item.line, data));
});
});

在 getDetails() 中

function getDetails(line, item)
{
var deferred = Q.defer();
var result = [];
ovh.request('GET', '/telephony/*******/service/' + line + '/voiceConsumption/' + item, function (err, fetched_data)
{
if (!err)
{
result = {
'line': line,
'consumption_id': item,
'type': fetched_data.wayType,
'calling': fetched_data.calling,
'called': fetched_data.called,
'plan_type': fetched_data.planType,
'destination_type': fetched_data.destinationType,
'date': fetched_data.creationDatetime,
'duration': fetched_data.duration,
'price': fetched_data.priceWithoutTax
};
// console.log("RESULT: ",result);
deferred.resolve(result);
}
else
{
deferred.reject(err);
console.log(err);
}
});
return deferred.promise;
}

循环之后:

Q.allSettled(promises).done(function(final_result)
{
final_result.forEach(function (promise_fetch){
if (promise_fetch.state != 'fulfilled')
{
console.log("ERREUR Merge");
}
else
{
all_consumptions.push(promise_fetch.value);
}
deferred.resolve(all_consumptions);
});
return deferred.promise;
});

使用这段代码,我得到了专门的日志错误:400

我会尝试使用一些 setTimeOut 来减慢我的循环,在这种情况下,获取成功,但我的 q.allSettled 被跳过...我真的迷路了...

有什么想法可以改进我的 promise 句柄/循环句柄吗?我很确定你已经知道了,但这是我学习 JS 和 NodeJS 的第一周。

非常感谢您的帮助...

最佳答案

您可以使用 promise 循环,如下所示:

function pwhile(condition, body) {
var done = Q.defer();

function loop() {
if (!condition())
return done.resolve();
Q.when(body(), loop, done.reject);
}

Q.nextTick(loop);

return done.promise;
}

然后,您的代码将是:

list_consumptions.forEach(function (item) {
var i = 0;
pwhile(function() { return i < item.consumptions.length; }, function() {
i++;
return getDetails(item.line, data)
.then(function(res) {
all_consumptions.push(res);
})
.catch(function(reason) {
console.log("ERREUR Merge");
});
}).then(function() {
// do something with all_consumptions here
});
});

关于javascript - q.allSettled 有默认超时吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32827026/

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