Examining Question 1
.then(callback)
will generate a fresh promise that resolves to the output of callback
, or if the result is another promise, it will resolve to that promise's value once settled. This technique is useful for sequencing asynchronous operations. For instance, in this scenario:
function myFunction() { return promise; }
the code snippet below will execute myFunction
consecutively 10 times
var result = $q.resolve();
for (var i = 0; i < 10; ++i) {
result = result.then(myFunction);
}
result.then(function () { /* myFunction has been executed 10 times */ })
Inquiry Question 2
In this case, recursion becomes necessary as the exact number of iterations is unknown. When dealing with a similar myFunction
setup as previously mentioned:
function wrapper() {
var deferred = $q.defer();
iter();
function iter(res) {
// Skip first iter() call, and wait for acceptable res
if (result !== void 0 && /* res meets criteria */) {
return deferred.resolve(res);
}
// Recursive call
return myFunction().then(iter);
}
return deferred.promise;
}
wrapper().then(function (res) { /* res meets criteria */ })
Note that in such scenarios, promises may not necessarily provide an advantage over traditional callbacks.