在 Jscript 中为 Q.all() 构建一个动态函数数组

Building a dynamic array of functions for Q.all() in Jscript

本文关键字:一个 动态 函数 数组 构建 all Jscript 中为      更新时间:2023-09-26

我正在尝试将可变数量的函数传递给Q.all((

如果我手动对数组进行编码,它可以正常工作 - 但是我想在循环中构建它,因为系统在运行时之前不知道调用该函数多少次 - 并且需要为每个 AJAX 调用传递不同的 ID。

我尝试了各种方法都没有成功(例如 array[i] = function() {func} ( - 我想eval()可能是最后的手段。

任何帮助都会非常有帮助。

// Obviously this array loop wont work as it just executes the functions in the loop
// but the idea is to build up an array of functions to pass into Q
var arrayOfFunctions = [];
for(var i in NumberOfPets) {
    arrayOfFunctions[i] = UpdatePets(i);
}

// Execute sequence of Ajax calls
Q.try(CreatePolicy)
.then(updateCustomer) 
.then(function() {
    // This doesn't work - Q just ignores it
    return Q.all(arrayOfFunctions)
    // This code below works fine (waits for all pets to be updated) - I am passing in the ID of the pet to be updated
    // - But how can I create and pass in a dynamic array of functions to achieve this?
    // return Q.all([UpdatePets(1), UpdatePets(2), UpdatePets(3), UpdatePets(4), UpdatePets(5), UpdatePets(5)]);
    }) 
.then(function() {
    // do something
})
.catch(function (error) {
    // error handling
})
.done();

提前谢谢。

>Q.all不需要函数数组,而是期望一系列承诺。用

Q.try(CreatePolicy)
.then(updateCustomer) 
.then(function() {
    var arrayOfPromises = [];
    var numberOfPets = pets.length;
    for (var i=0; i<numberOfPets; i++)
        arrayOfPromises[i] = updatePet(pets[i], i); // or something
    return Q.all(arrayOfPromises)
}) 
.then(function() {
    // do something
})
.catch(function (error) {
    // error handling
});