Syncing Angular Promises

Shane Edwards's picture
7, Aug, 2015 by Shane Edwards

Syncing Angular Promises

0 comment
Syncing Angular Promises

I recently had this problem and made a utility called 'syncPromises'. This basically works by sending what I called an "instruction list", which would be array of functions to be called in order. You'll need to call the first then() to kick things of, dynamically attach a new .then() when the response comes back with the next item in the instruction list so you'll need to keep track of the index. This I found gave us the most flexibility.

// instructionList is array.
function syncPromises (instructionList) {
var i = 0,
defer = $q.defer();

function next(i) {

// Each function in the instructionList needs to return a promise
instructionList[i].then(function () {
var test = instructionList[i++];
if(test) {
next(i);
}
});
}

next(i);

return defer.promise;
}

You can automatically push operations etc to build an instruction list and you're also able to append as many .then() responses handlers in the callee function. You can also chain multiple syncPromises functions that will all happen in order.