gpt4 book ai didi

node.js - 异步 forEachOfLimit 函数不限制集合的迭代

转载 作者:搜寻专家 更新时间:2023-11-01 00:41:18 25 4
gpt4 key购买 nike

我的问题是 - async.forEachLimit 函数没有限制 n 次迭代。

我正在为我的收藏执行异步任务。这个我试过了。。。

var async = require('async');
console.log(finalLocations.length); //Expecting 4

所以我需要执行循环 3 次,因为我在同一操作中使用键的当前值和键的下一个值。它将导致最后一次迭代未定义。

因为我迭代的时间少了 1 个集合的长度。我用过这个。如果长度为 4,我想将它迭代 3 次,即 0,1,2。这样 -

async.forEachOfLimit(finalLocations, finalLocations.length - 2, function (value, key, next) {

console.log(key + ': ' + value);

//distanceMatrix.matrix(finalLocations[key], finalLocations[key + 1], function (err, successiveDistances) {
// if (err) return next(err);
// if (!successiveDistances || successiveDistances.status !== 'OK') {
// return next({status: 400, message: 'No distance'});
// }
//
// if (successiveDistances.rows[0].elements[0].status === 'OK') {
// totalTime = totalTime + successiveDistances.rows[0].elements[0].duration.value;
// totalDistance = totalDistance + successiveDistances.rows[0].elements[0].distance.value;
// }
// next();
//});
next();
}, function (err) {
console.error('Printing error here :- ' + err);
if (err) return callback(err);

console.log('Successfully completed all iterations !!');
callback(null, {totalTime: 0, totalDistance: 0});
});

或者如果简单的话我可以发布。

async.forEachOfLimit([1,2,3,4], 2, function (value, key, next) {
console.log(key + ': ' + value);
next();
}, function (err) {
console.error('Printing error here :- ' + err);
if (err) return callback(err);

console.log('Successfully completed all iterations !!');
callback(null, {totalTime: 0, totalDistance: 0});
});

它的控制台是:

0: 1
1: 2
2: 3
3: 4
Printing error here :- null
Successfully completed all iterations !!

最佳答案

async.forEachOfLimit() 迭代您传递给它的整个集合。第二个参数(限制值)仅指定同时进行多少次迭代。因此,如果您向它传递一个包含 4 个元素且限制为 3 个元素的数组,它将开始前 3 个操作,然后当其中一个完成时,它将开始第四个。

这就是该函数的编码方式。

如果您只想迭代集合的一部分,您可以拼接集合的部分副本并将其传递给类似 async.each() 的东西。

关于node.js - 异步 forEachOfLimit 函数不限制集合的迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33604509/

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