JavaScript循环承诺在参数中使用数组进行迭代

javascript loop promises iterating with array in arguments

本文关键字:数组 迭代 循环 承诺 参数 JavaScript      更新时间:2023-09-26

我正在尝试遍历要完成的AsynWork数组。并且不能用同时完成的异步工作淹没系统。所以我试图一个接一个地做承诺。我的问题是我需要遍历一个值数组,以便每个异步都适用于数组的每个值。我设法用这段代码做到了,但它适用于我的具体情况。不能让它泛泛而谈。使它可重用于其他类型的数组的方法是什么?我已经看到了一些使用 array.reduce 然后承诺的解决方案,但无法弄清楚。也看过Q的例子,但没有使用,如果可以用简单的javascript完成会更好。

我的代码:

function doSomething(ObjIn1, ObjIn2) {
    return new Promise(function(resolve, reject) {
        console.log("doSomething: ObjIn1: " + ObjIn1 + "  ObjIn2: " + ObjIn2);
        setTimeout(function() {
            console.log("doSomething Done: ObjIn1: " + ObjIn1 + "  ObjIn2: " + ObjIn2);
            resolve(ObjIn1, ObjIn2);
        }, 500);
    })
}
function LoopPromises(Function2Loop, functionOptions, Counter, Max) {
    console.log("Counter: " + Counter);
    if (Counter < Max) {
        Function2Loop.apply(this, [functionOptions[0][Counter], functionOptions[1]]).then(function() {
            Counter++;
            LoopPromises(Function2Loop, functionOptions, Counter, Max);
        });
    }
}
LoopPromises(doSomething, [
    ["A1", "A2", "A3"], "ARG2TESTE"
], 0, 3)

你把这个:)想多了带参数的函数与不带参数的函数在带参数的函数上闭合相同,因此:

a(1,2,3,4);

(() => a(1,2,3,4))(); 

除了也许可以忽略不计的慢。我假设您需要为任意数量的承诺排队。如果您需要为固定号码执行此操作 - 您可以在它们之间then。让我们看看如何做到这一点:

// runs fn on the array elements in sequence, but 
function sequence(fns) { // fns - functions returning promises
    return fns.reduce((prev, nextFn) => { // 'fold' the array
        return prev.then(nextFn); // after the previous is done, execute the next
    }, Promise.resolve()); // start with an empty promise
}

确保您首先了解减少。为了方便起见 - 让我们看一个没有它的例子:

function sequence(fns) { // fns - functions returning promises
    var queue = Promise.resolve();
    fns.forEach(fn => queue = queue.then(fn));
    return queue;
}

我们正在遍历我们的工作(函数)数组,并一个接一个地执行它们,在上一个返回的承诺解决后执行下一个。

其中,值根据承诺解析(通过 then)相互等待。这将允许您执行以下操作:

sequence([
   () => new Promise(r => setTimeout(r, 500));
   () => console.log("I only run after the previous work completed");
]);