I have a task that requires the browser to make N requests to the server, where the requests must be synchronous and start only after the previous request has completed.
One way to achieve this is by writing a function with a for loop and recursively calling it, but it can lead to callback hell and not very elegant. I am looking for a more elegant solution.
I came across deferred objects which some say can help avoid callback hell. I want something similar to using setTimeout to simulate an asynchronous request:
function foo1(some) {
debugger;
setTimeout(function foo1async() {
debugger;
deffered.resolve();
}, 500);
return deffered.promise;
}
function foo2(some) {
debugger;
setTimeout(function foo2async() {
debugger;
deffered.reject();
}, 500);
return deffered.promise;
}
function foo3() {
debugger;
setTimeout(function foo3async() {
debugger;
deffered.resolve();
}, 500);
return deffered.promise;
}
var deffered;
function doChain() {
debugger;
deffered = $q.defer();
var promise = deffered.promise;
promise.then(foo1);
promise.then(foo2);
promise.then(foo3);
promise["finally"](function () {
debugger;
});
deffered.resolve();
}
- I expect foo1 to be called, then foo1async will be called and resolve the deferred object.
- foo2 should be called next, followed by foo2async. 3.Now, I expect that foo3 wouldn't be executed because the deferred is rejected in foo2async. After that, I expect the code in the finally section to be called.
However, what actually happens is that foo1, foo2, and foo3 are all called. Then the code in the finally section runs. Finally, foo1async, foo2async, and foo3async functions are called.
I want to achieve my expected behavior by implementing something like this:
for(var i = 0; i < N; i++) {
(function (iter) {
promise.then(function () {
foo(iter);
});
})(i);
}