Chain promises with $ q in Angular

I am trying to bind promises so that doQuery (0) does doQuery (1), etc. sequentially to doQuery (9).

My problem is that I always equal 10 in the callback function.

doQuery (0) executes the doQuery (10) command.

How to pass each value i in a callback function?

var promise = doQuery(0); for (var i = 1; i < 10; i++) { promise = promise.then(function() { doQuery(i); }); }; 
+6
source share
2 answers

Since you are using Angular.js, you should use the binding function here:

 var promise = doQuery(0); for (var i = 1; i < 10; i++) { promise = promise.then(angular.bind(null, doQuery, i)); } 

Without relying on Angular.js, you can use closure to make a copy of i for each callback function (instead of all using the same copy of i in the outer scope):

 var promise = doQuery(0); for (var i = 1; i < 10; i++) { promise = promise.then(function(i){ return function(){ doQuery(i); }; }(i)); } 

In modern Javascript engines, you can also use your own Function.prototype.bind :

 var promise = doQuery(0); for (var i = 1; i < 10; i++) { promise = promise.then(doQuery.bind(null, i)); } 
+5
source

You need to return every promise in a chain with a then callback, otherwise it will most likely fail. To pass the correct i value for each callback, see Closing JavaScript inside loops is a simple practical example .

 var promise = doQuery(0); for (var i=0; i<10; i++) (function(ii) { promise = promise.then(function() { return doQuery(ii); }); })(i); 
+2
source

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


All Articles