My task is to perform several asynchronous processes in angularjs sequentially. Their number is not known in advance.
As an example: the path is passed to the procedure and you need to create all the folders sequentially, since The next folder can only be created in the previous one. In this case, you need to wait for completion.
I did this through the recursive _manager
call, the procedure works, but does not report the completion to start.
.factory('TEST_F', function ($timeout, $q) { var isStop = false; var stop = function () { isStop = true; console.log('stop loop'); }; var start = function () { console.log('start loop'); isStop = false; var i = 0; _manager(i) .then(function (data) { console.log('---> resolve, i = ' + data.i); }, function (data) { console.log('---> reject, i = ' + data.i); }); }; var _manager = function (i) { var deferred = $q.defer(); _doer() .then(function (data) { i++; console.log('isStop = ' + isStop, 'i = ' + i); if (data.state === 'ok' && !isStop) { //deferred.resolve({state: 'ok', i: i}); return _manager(i); } else { deferred.reject({state: 'error', i: i}); return {state: 'error', i: i}; } }, function (data) { deferred.reject({state: 'error', i: i}); return {state: 'error', i: i}; }); return deferred.promise; }; var _doer = function () { var deferred = $q.defer(); $timeout(function () { console.log('loop'); }, 2000) .then(function (data) { console.log('+2 sec'); deferred.resolve({state: 'ok'}); }) ; return deferred.promise; }; return { stop: stop, start: start } })
Tell me please, how can you implement the sequential execution of asynchronous procedures?
_manager
stringdeferred.resolve({state: 'ok', i: i});
commented out? - Regent.resolve()
) anywhere? In this case, you need to pass thedeferred
object to recursive function calls and do.resolve()
in the last one.return
inside a function in.then()
useless. - Regent_manager()
should always do.reject()
, then the problem is that.reject()
is done fordeferred
from the last_manager()
, and not from the first, whilestart()
waiting for the result of the firstdeferred
. - Regent