I recently posted a question on Stack Overflow that was somewhat similar to this, but the current issue requires chaining the requests serially. I have two asynchronous requests where the second request depends on the result of the first request in order to send its query.
var Db.get = function(key){
var deferred = $q.defer();
//send async req
var req = ....
req.success = function(d){
deferred.resolve(d)
};
req.failure = function(d){
deferred.reject(d)
}
return deferred.promise;
}
var someFn = function(id){
Db.get(id, "abc")
.then(function (d) {
console.log("At 1")
Db.get(d.id, "def")
.then(function (d) {
console.log("At 2")
return d
}, function (e) {
//error
});
}, function (e) {
//error
});
console.log("At 3")
};
In my understanding, I expected console.log("At 3")
not to be printed in the success scenario as I return after console.log("At 2")
. However, when I run the code, the following order is seen in the console:
console.log("At 1")
console.log("At 3")
console.log("At 2")
I thought that the then
method would block until it receives a response from the promise returned by get()
, ensuring that everything in someFn
executes serially. Is this assumption incorrect? What is the best way to chain two asynchronous operations that use promises to run serially?
Thank you.
EDIT:
I attempted what Ketan suggested regarding Chaining Ajax calls in AngularJs.
var someFn = function(id){
Db.get(id, "abc")
.then(function (d) {
console.log("At 1")
return Db.get(d.id, "def")
}).then(function (d) {
console.log("At 2")
return d
}, function (e) {
//error
return null;
}).then(function (d) {
return d;
});
console.log("At 3")
};
Even after making a call like
var res = someFn(1)
console.log(res) /// undefined
The Chrome terminal displays At 2
after undefined
. I am unsure why the result returned by someFn
is not assigned to res
.