Make Javascript Execution Synchronous - A Scenario in Angularjs
Last week I came to deal with a problem in my angularjs application. I want to execute a code block only after getting the response from rest service call. This code block is not inside success/failure call back function, but it is below service call code as below.
function function1() {
//rest call
dataService.serviceCall().then(function (data) {
console.log("label a")
}, function (error) {
console.log("call failed"+ error);
});
console.log("label b")
}
I want to print "label b" only after printing "label a". But now, as javascript is asynchronous, 'label b' is first printed then 'label a'. It is not waiting for the response of the service call.
To print "label b" only after printing "label a", I found two solutions,
1.
Put the label a code inside callback function.
eg :
function1() {
//rest call
dataService.serviceCall().then(function (data) {
console.log("label a");
printB();
}, function (error) {
console.log("call failed"+ error);
});
var printB = function(){
console.log("label b");
}
}
In real case, the code block was not a single line code, that's why /i put it outside service call. If it is a small one i could have been included in success callback function it self. Here I moved all the code into a new function in side function itself, so that I will get the all local references. Then I called function inside success callback function.
I added a new function syncCall. This will call function1. Js promises or deffered is used to make it synchronous. If response is received successfully, 'label a' is printed, promise is resolved and returned. On successful resolution of promise, 'label b' is printed.
eg:
syncCall();
function syncCall() {
var deferred = $q.defer();
function1(deferred).then(function () {
console.log("label b");
}, function () {
console.log("err");
});
}
/* Filter items */
function function1(deferred) {
dataService.serviceCall().then(function (data) {
console.log("label a");
deferred.resolve();
}, function (error) {
console.log("call failed"+ error);
deferred.reject();
});
return deferred.promise;
}