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

时间:2013-10-10 09:42:43

标签: javascript arrays promise deferred q

我正在尝试将可变数量的函数传递给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();

提前致谢。

1 个答案:

答案 0 :(得分:7)

Q.all不期望一系列函数,而是一系列promise。使用

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
});