JSFiddle - React, Tailwind, and code Playground
JavaScript
function test($timeout, $q) {
var isStop = false;
var stop = function() {
isStop = true;
console.log('stop loop');
};
var start = function() {
console.log('start loop');
isStop = false;
_manager(0).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(i).then(function(data) {
i++;
console.log('isStop = ' + isStop, 'i = ' + i);
if (data.state === 'ok' && !isStop && i < 7) { // доп. условие остановки
//deferred.resolve({state: 'ok', i: i});
return _manager(i);
} else {
//deferred.resolve({state: 'end', i: data.i});
return {
state: 'end',
i: data.i
};
}
}, function (data) {
//deferred.reject({state: 'error', i: data.i});
return {
state: 'error',
i: data.i
};
})
.then(function (data) {
if (data.state === 'ok') {
deferred.resolve({
state: 'ok',
i: data.i
});
} else if (data.state === 'end') {
deferred.resolve({
state: 'end',
i: data.i
});
} else {
deferred.resolve({
state: 'error',
i: data.i
});
}
});
return deferred.promise;
};
var _doer = function() {
var deferred = $q.defer();
$timeout(function() {
console.log('loop');
}, 2000)
.then(function(data) {
console.log('+2 sec');
...