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

I am trying to pass a variable number of functions to Q.all ()

It works fine if I encode the array manually - however, I want to create it in a loop, since the system will not know how many times to call the function before execution - and it needs to pass a different identifier to it for each AJAX call.

I tried various methods without success (for example, array[i] = function() {func} ). I think eval() may be the last.

Any help would be very 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.

+6
source share
1 answer

Q.all does not 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 }); 
+7
source

Source: https://habr.com/ru/post/955656/


All Articles