Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to to pass a variable number of functions into Q.all()

It works fine if I code the array manually - however I want to build it up in a loop as the system wont know how many times to call the function until runtime - and needs to pass a different ID into it for each AJAX call.

I've tried various methods with no success (e.g. array[i] = function() {func}) - I guess eval() could be a last resort.

Any help would be massively helpful.

// 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();

Thanks in advance.

like image 268
Tim Hooper Avatar asked Oct 10 '13 09:10

Tim Hooper


1 Answers

Q.all doesn't expect an array of functions, but an array of promises. Use

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
});
like image 138
Bergi Avatar answered Sep 21 '22 02:09

Bergi