Working with promise - angularjs - angularjs

How to rewrite this code, to get the desired o/p.
I would like to use the AgentReply object after filling in the data.
Inside the switch case, this object has data. But once outside, it is null again. Understood that it is because of the async,
But what should I do, to be able to use 'AgentReply' once it has data.
$scope.ActionItems = function (actionItem) {
var AgentReply = {};
switch (actionItem) {
case "SendOTP":
var SentStatus = "";
DataFactory.SendOTP('39487539847')
.then(function (response) {
SentStatus = JSON.parse(JSON.parse(response.data));
SendOTPFailed();
}, function (error) {
});
break;
}/*End of switch*/
function SendOTPFailed(){
if (SentStatus == "200") {
AgentReply = {
IsCustomer: false,
UserText: "Request Failed.",
}
}
}
if (Object.keys(AgentReply).length > 0) {
//do something with AgentReply
}
}

Just pass a function in to where the AgentReply is available, and define it underneath, ie:
$scope.ActionItems = function (actionItem) {
var AgentReply = {};
switch (actionItem) {
case "SendOTP":
var SentStatus = "";
DataFactory.SendOTP('39487539847')
.then(function (response) {
SentStatus = JSON.parse(JSON.parse(response.data));
if (SentStatus == "200") {
AgentReply = {
IsCustomer: false,
UserText: "Request Failed.",
}
}
doSomethingWithAgentReply(AgentReply);
}, function (error) {
});
break;
}
console.log(AgentReply); //null here
function doSomethingWithAgentReply(reply) {
if (Object.keys(reply).length > 0) {
//do something with AgentReply
}
}
}

If you need to use this code :
if (Object.keys(AgentReply).length > 0) {
//do something with AgentReply
}
}
Outside the .then() function :
DataFactory.SendOTP('39487539847')
.then(function (response) {
})
You can try this:
$scope.ActionItems = function (actionItem) {
var def = jQuery.Deferred();
var AgentReply = {};
switch (actionItem) {
case "SendOTP":
var SentStatus = "";
DataFactory.SendOTP('39487539847')
.then(function (response) {
SentStatus = JSON.parse(JSON.parse(response.data));
if (SentStatus == "200") {
AgentReply = {
IsCustomer: false,
UserText: "Request Failed.",
}
def.resolve(AgentReply);
}
console.log(AgentReply); //available here
}, function (error) {
def.reject(error);
});
return def.promise();
break;
}
//console.log(AgentReply); //null here
//if (Object.keys(AgentReply).length > 0) {
//do something with AgentReply
// }
//}
// This is unusable in this case.
The usage is:
var someActionItem = 'SomeActionItemInfo';
$scope.ActionItems(someActionItem)
.then(function(agentReply) {
if (Object.keys(agentReply).length > 0) {
//do something with agentReply
}
}, function(error));
EDIT:
$scope.ActionItems is the same function. What happening when you using promise?
First you defining the deffer object. var def = jQuery.Deferred(). This object is at jQuery, but all frameworks/libraryies that support promise working at the same way.
As you see, you returning def.promise(). That is the object which contain .then property. Because of that obj you can use $scope.ActionItems().then() method. That actually make def.promise().
And inside your async code (this code that consuming some time and it's not executed immediately) you defining def.resolve() or def.reject().
When the work is done. You calling def.resolve(withSomeData) and this will activate .then() method to the $scope.ActionItems.
For example:
var foo = null;
function doPromise() {
var def = jQuery.Deferred();
setTimeout(function(){
foo = 2;
def.resolve(foo + 1) // This will call the .then() method with foo + 1
}, 500);
return def.promise();
}
doPromise();
console.log(foo) // foo = null here. cuz the function waiting 500ms.
// Here the .then() method will be executed after ~500+ ms.
doPromise().then(function(fooValue) {
console.log(fooValue) // foo value = 3 here. cuz function is done
});

Related

A function does not wait for another function to execute

This is my service
var validateEmailService=function (validateEmailUrl,validateEmailParameters,email) {
var url=validateEmailUrl +'?';
angular.forEach(validateEmailParameters,function (value,key) {
url=url +key +'='+ value.parameter +'&';
});
url=url+'email='+email;
$http.get(url).then(function (value) {
var result = value;
var smtpCheck = result.data.smtp_check;
var mxRecordsCheck = result.data.mx_found;
// console.log(smtpCheck ,mxRecordsCheck);
if (smtpCheck === true && mxRecordsCheck === true){
//console.log('In');
return true;
}
//console.log('Out');
});
};
var sendEmailService=function (sendEmailApiUrl,emailData,config,email,firstName,lastName) {
emailData = JSON.stringify(emailData);
emailData = emailData.replace("%%Email%%", email);
emailData = emailData.replace("%%FirstName%%", firstName);
emailData = emailData.replace("%%LastName%%", lastName);
emailData = JSON.parse(emailData);
$http.post(sendEmailApiUrl, emailData, config);
};
return {
validateEmailService: validateEmailService,
sendEmailService: sendEmailService
};
And I have called these functions here in the controller
var validate = emailService.validateEmailService(validateEmailUrl, validateEmailParameters,$scope.patient.Email);
if (validate === true) {
emailService.sendEmailService(sendEmailApiUrl, emailData, config,$scope.patient.Email,$scope.patient.givenName,$scope.patient.familyName);
messagingService.showMessage("info", "REGISTRATION_LABEL_SAVED");
$state.go("patient.edit", {
patientUuid: $scope.patient.uuid
});
}
else {
alert('Email does not exist');
}
So when the if statement is executed validate does not contain anything and it automatically goes to the else part even when validate should be true.
You should use the promise instead, the $http.get is asynchronous
var validateEmailService=function (validateEmailUrl,validateEmailParameters,email) {
var url=validateEmailUrl +'?';
angular.forEach(validateEmailParameters,function (value,key) {
url=url +key +'='+ value.parameter +'&';
});
url=url+'email='+email;
// IMPORTANT PART: USE RETURN
return $http.get(url).then(function (value) {
var result = value;
var smtpCheck = result.data.smtp_check;
var mxRecordsCheck = result.data.mx_found;
// console.log(smtpCheck ,mxRecordsCheck);
if (smtpCheck === true && mxRecordsCheck === true){
//console.log('In');
return true;
}
//console.log('Out');
});
};
And then in your controller:
emailService.validateEmailService(validateEmailUrl, validateEmailParameters,$scope.patient.Email).then(function(validate){
if (validate === true) {
emailService.sendEmailService(sendEmailApiUrl, emailData, config,$scope.patient.Email,$scope.patient.givenName,$scope.patient.familyName);
messagingService.showMessage("info", "REGISTRATION_LABEL_SAVED");
$state.go("patient.edit", {
patientUuid: $scope.patient.uuid
});
} else {
alert('Email does not exist');
}
})
Also, see this link about promises

Can't change value of $scope after get request

I am looking for a possible solution to the below, I have an array that has an assigned watcher. My issue is changing the $scope after receiving a response from a http get request. $scope is always undefined, I need to change the value there in real time. Any suggestions would be greatly appreciated!
$scope.$watch('user.tags', function (newVal, oldVal) {to invalid until the
$scope.tags_valid = true;
// Loop through array and validate length
for (var i = 0; i < $scope.user.tags.length; i++) {
if ($scope.user.tags[i].data.length != 24) {
$scope.tags_valid = false;
return;
}
// Check if already exists
$http.get("api/registration/TagExists", { params: { Tag_Id: $scope.user.tags[i].data } }).success(function (response) {
if (response == "true") {
// $scope is always undefined here
$scope.user.tags[i].is_valid = false;
$scope.tags_valid = false;
} else if (response == "false") {
// $scope is always undefined here
$scope.user.tags[i].is_valid = true;
}
});
}
}, true);
Actually what is undefined is the user tag at [i].
Because of the function scope of the variable, the i will be equal to the length of the array before any response from server arrives.
You could wrap the server call in a function that would accept the index or the actual tag as an argument. Like checkTag(tag) in which you make the call.
Example code:
function checkTag(tag) {
$http.get("api/registration/TagExists", { params: { Tag_Id: tag.data } }).success(function (response) {
if (response == "true") {
tag.is_valid = false;
$scope.tags_valid = false;
} else if (response == "false") {
tag.is_valid = true;
}
});
}

Cordova.writefile function doesn't run, but doesn't give an error

I'm making an ionic application. I have a function called scope.win() that's supposed to fire when a quiz is finished, and then update the JSON file to add that quiz to the number of finished quizzes but it doesn't run properly.It doesn't give off any error. The function just stops running at a certain point and the app keeps going and nothing is happening.
This is the controller's file
angular.module('controllers', ['services'])
.controller('MainCtrl', function ($scope, $state, data) {
$scope.$on('$ionicView.enter', function () {
data.create();
});
$scope.chapter = data.chapterProgress();
})
.controller("BtnClick", function ($scope, lives, data, $cordovaFile, $ionicScrollDelegate) {
var live = 3;
var clickedOn = [];
var numQuestions;
$scope.part2Cred = false;
$scope.part3Cred = false;
$scope.part4Cred = false;
$scope.part5Cred = false;
$scope.part6Cred = false;
$scope.part7Cred = false;
$scope.part8Cred = false;
$scope.part9Cred = false;
$scope.part10Cred = false;
$scope.partQCred = false;
$scope.setNumQuestions = function(num){
numQuestions = num;
}
$scope.updatelives = function (){
//grabs the element that is called liv then updates it
var livesOnPage = document.getElementById('liv');
livesOnPage.innerHTML = live;
}
$scope.wrong = function (event){
var selec = document.getElementById(event.target.id);
if(clickedOn.includes(selec)){}
else{
selec.style.color = "grey";
clickedOn.push(selec);
live = live - 1;
if(live == 0){
$scope.gameover();
}
else{
$scope.updatelives();
}
}
}
$scope.right = function (event,chapter, section){
var selec = document.getElementById(event.target.id);
if(clickedOn.includes(selec)){}
else{
selec.style.color = "green";
clickedOn.push(selec);
numQuestions = numQuestions - 1;
if(numQuestions === 0){
$scope.win(chapter, section);
}
}
}
$scope.gameover = function(){
alert("game over please try again");
live = 3;
$ionicScrollDelegate.scrollTop();
$scope.partQCred = false;
$scope.part1Cred = !$scope.part1Cred;
for(i = 0; i< clickedOn.length;i++){
clickedOn[i].style.color = "rgb(68,68,68)";
}
}
$scope.win = function (chapter, section) {
alert("Well Done");
var data = data.chapterProgress(); // It is at this point that the //function stops running without giving off any error.
alert("Good Job");
var sectionsComplete = data[chapter].sectionsCompleted;
var totalsection = data[chapter].totalSections;
if (section === totalSection) {
window.location.href = "#/chapter1sections";
return;
}
if (section > sectionsComplete) {
data[chapter].sectionsCompleted += 1;
var url = "";
if (ionic.Platform.isAndroid()) {
url = "/android_asset/www/";
}
document.addEventListener('deviceready', function () {
$cordovaFile.writeFile(url + "js/", "chapters.json", data, true)
.then(function (success) {
// success
alert("Json file updated")
window.location.href = "#/chapter1sections";
}, function (error) {
// error
});
});
}
}
});
Here is the Services file. It seems to run fine but it is referenced a lot in the problematic sections of code in the controllers so I figured it was necessary to put it here.
angular.module('services', [])
.service('lives', function () {
var live = 3;
return {
getlives: function () {
return live;
},
setlives: function (value) {
live = value;
}
};
})
.service('data', function ($cordovaFile, $http) {
var url = "";
if (ionic.Platform.isAndroid()) {
url = "/android_asset/www/";
}
return {
//Run this function on startup to check if the chapters.json file exists, if not, then it will be created
create: function () {
var init = {
"one": {
"sectionsCompleted": 0,
"totalSections": 4
},
"two": {
"sectionsCompleted": 0,
"totalSections": 1
}
};
$cordovaFile.writeFile(url + "js/", "chapters.json", init, false)
.then(function (success) {
// success
}, function (error) {
// error
});
},
chapterProgress: function () {
return $http.get(url + "js/chapters.json").success(function (response) {
var json = JSON.parse(response);
return json;
}, function (error) {
alert(error);
});
}
}
});
Thank You so much for the help and time.

Call multiple web api using Angular js one by one

I have a scenario in which there is 8 web api's called as :
#1
Sync Local DB from server DB (response will RETURN a List=> myList)
If (myList.Length > 0)
#1.1 Call web Api to Insert/Update Local DB
#2
Sync Server DB from Local DB (Request goes with a List=> myList)
If (myList.Length > 0)
#2.1 Call web Api to Insert/Update in Server DB (Response will RETURN a List=> newList)
If(newList.length > 0)
#2.2 Call web Api to Insert/Update in Local DB
I have two separate process For Head and Head Collection tables which synced with above process. So there is #3 and #4 scenario is also present.
I have call web api in the following manner...
syncHeadDataLogic();
syncHeadCollectionDataLogic();
I need that Head data should be synced first then HeadCollection data synced. But if there is no updated record for head then Head collection executed.
In my scenario my web apis called in any order but i need a order as I have described above. Kindly suggest me how I achieved this.
#Updated
//Sync Head
$scope.initializeController = function () {
if ($scope.online) {
//debugger;
syncHeadDataLogic();
syncHeadCollectionDataLogic();
}
};
function syncHeadDataLogic() {
HeadService.HeadSyncLocalDB(parseInt(localStorage.headRevision, 10), $scope.completeds, $scope.erroe);
};
$scope.SynServerDBCompleted = function (response) {
debugger;
$scope.HeadListForSync = response.HeadList;
var tempHeadCurrencyDetail = [];
if ($scope.HeadListForSync.length > 0) {
angular.forEach($scope.HeadListForSync, function (xx) {
xx.CurrencyId = xx.CurrencyServerId;
xx.Id = xx.HeadServerId;
angular.forEach(xx.HeadCurrencyDetail, function (yy) {
yy.CurrencyId = yy.CurrencyServerId;
yy.HeadId = xx.HeadServerId;
if (yy.Revision == -1)
tempHeadCurrencyDetail.push(yy);
});
xx.HeadCurrencyDetail = tempHeadCurrencyDetail;
});
var postData = { Revision: parseInt(localStorage.headRevision, 10), HeadList: $scope.HeadListForSync };
HeadService.SynServerDB(postData, $scope.completed, $scope.erroe);
}
else {
// alertsService.RenderSuccessMessage("There is no change in data after your last synchronization.");
}
};
$scope.requestErrorwer = function (response) {
debugger;
};
$scope.completed = function (response) {
debugger;
if (response.RevisionNo == localStorage.headRevision) {
syncHeadCollectionDataLogic();
// alertsService.RenderErrorMessage("There is newer version on the server. Please Sync from server first.", "MessageAlert");
}
else {
syncData(response);
}
};
$scope.completeds = function (response) {
debugger;
if (response.RevisionNo == localStorage.headRevision) {
syncHeadCollectionDataLogic();
// alertsService.RenderSuccessMessage("You are already working on the latest version", "MessageAlert");
}
else {
syncData(response);
}
//
var request = new Object();
HeadService.getAllHeadForRevision(request, $scope.SynServerDBCompleted, $scope.requestErrorwer);
};
$scope.erroe = function (response) {
debugger;
// alertsService.RenderErrorMessage("Data Synchronization Failed", "MessageAlert");
};
function syncData(data) {
debugger;
$scope.ReturnedRevisonNo = data.RevisionNo;
if (data.HeadList && data.HeadList.length > 0) {
var postData = { Revision: $scope.ReturnedRevisonNo, HeadList: data.HeadList, HeadRevision: $scope.ReturnedRevisonNo };
HeadService.AddUpdateHeadAfterSync(postData, $scope.cmpSync, $scope.Error);
}
else {
syncHeadCollectionDataLogic();
}
};
$scope.cmpSync = function (response) {
debugger;
localStorage.headRevision = $scope.ReturnedRevisonNo;;
alertsService.RenderSuccessMessage("The synchronization has been completed successfully.");
syncHeadCollectionDataLogic();
};
$scope.Error = function (response) {
debugger;
// alertsService.RenderErrorMessage(response.ReturnMessage);
// alertsService.SetValidationErrors($scope, response.ValidationErrors);
};
////////////Sync End
//Sync Head Collection
function syncHeadCollectionDataLogic() {
HeadService.HeadSyncLocalCollectionDB(parseInt(localStorage.headCollectionRevision, 10), $scope.completedCollections, $scope.erroeCollection);
};
$scope.SynServerDBCompletedCollection = function (response) {
$scope.HeadCollectionListForSync = response.HeadCollectionList;
if ($scope.HeadCollectionListForSync.length > 0) {
angular.forEach($scope.HeadCollectionListForSync, function (value, index) {
value.Id = value.HeadCollectionServerId;
angular.forEach(value.HeadCollectionDetails, function (v) {
v.CommittedCurrencyId = v.CommittedCurrencyServerId;
v.HeadId = v.HeadServerId;
v.WeightId = v.WeightServerId;
v.HeadCollectionId = value.HeadCollectionServerId; //change
angular.forEach(v.HeadCollectionAmountDetails, function (xx) {
xx.CurrencyId = xx.CurrencyServerId;
});
});
});
var postData = { Revision: parseInt(localStorage.headCollectionRevision, 10), HeadCollectionList: $scope.HeadCollectionListForSync };
HeadService.SynServerCollectionDB(postData, $scope.completedCollection, $scope.erroeCollection);
}
else {
// alertsService.RenderSuccessMessage("There is no change in data after your last synchronization.");
}
};
$scope.requestErrorwerCollection = function (response) {
};
$scope.completedCollection = function (response) {
if (response.RevisionNo == localStorage.headCollectionRevision) {
// alertsService.RenderErrorMessage("There is newer version on the server. Please Sync from server first.", "MessageAlert");
}
else {
syncDataCollection(response);
}
};
$scope.completedCollections = function (response) {
if (response.RevisionNo == localStorage.headCollectionRevision) {
// alertsService.RenderSuccessMessage("You are already working on the latest version", "MessageAlert");
}
else {
syncDataCollection(response);
}
var request = new Object();
HeadService.getAllHeadCollectionForRevision(request, $scope.SynServerDBCompletedCollection, $scope.requestErrorwerCollection);
};
$scope.erroeCollection = function (response) {
// alertsService.RenderErrorMessage("Data Synchronization Failed", "MessageAlert");
};
function syncDataCollection(data) {
$scope.ReturnedRevisonNo = data.RevisionNo;
if (data.HeadCollectionList && data.HeadCollectionList.length > 0) {
var postData = { Revision: $scope.ReturnedRevisonNo, HeadCollectionList: data.HeadCollectionList, HeadRevision: $scope.ReturnedRevisonNo };
HeadService.AddUpdateaHeadCollectionAfterSync(postData, $scope.cmpSyncCollection, $scope.ErrorCollection);
}
};
$scope.cmpSyncCollection = function (response) {
localStorage.headCollectionRevision = $scope.ReturnedRevisonNo;;
alertsService.RenderSuccessMessage("The synchronization has been completed successfully.");
$scope.initializeController();
};
$scope.ErrorCollection = function (response) {
// alertsService.RenderErrorMessage(response.ReturnMessage);
// alertsService.SetValidationErrors($scope, response.ValidationErrors);
}
//End
I need that Head data should be synced first then HeadCollection data synced. But if there is no updated record for head then Head collection executed.
What you need is chained promises. Try this (I'm giving you pseudocode for now):
HeadService.HeadData
|-----------------|
HeadCollection(headDataResult)
|------------------|
finalHandler(headCollectionResult)
|------------------|
HeadService.HeadData()
.then(HeadService.HeadCollection) // return or throw Err if headDataResult is empty
.then(finalHandler);
Here, the order of execution of the promises will be predictable, and sequential. Also, each promise will be returned the resolved value of the previous promise
AngularJS as you can see in the documentation here, uses Promises out of the box with the $http injectable. You can define a factory like so:
// Factory code
.factory("SampleFactory", function SampleFactory($http) {
var sampleFactoryObject = {};
sampleFactoryObject.getSomething = function() {
return $http.get('/someUrl');
}
sampleFactoryObject.getSomething.then(function resolveHandler(res) {
return res;
},
function rejectHandler(err) {
throw new Error(err);
});
sampleFactoryObject.getSomethingElse = function() {
return $http.get('/someOtherUrl');
}
sampleFactoryObject.getSomethingElse.then(function resolveHandler(res) {
return res;
},
function rejectHandler(err) {
throw new Error(err);
});
return sampleFactoryObject;
});
// Controller code
.controller('myController', function myController(SampleFactory) {
SampleFactory.getSomething()
.then(SampleFactory.getSomethingElse())
.then(finalHandler);
var finalHandler = function(resultOfGetSomethingElse) {
console.log(resultOfGetSomethingElse);
}
});

NodeJS callback: How to make the call wait for mongodb query result

I have a registration dialog where when the user enters username and password I need to check the DB whether the user is present
or not. But when I am validation for the same my call does not hold back until I get the results from the server.
After searching for a while I got to know about callbacks. So I have added a call back inside this.isUser method.
And it is successful. But now doRegistration method is not synchronous with the isUser method.
How to make all my calls synchronous?
this.doRegistration = function(uname, pwd, confirmPwd) {
if(this.isUser(uname)) {
return "USER_EXISTS";
} else {
saveUser(uname, pwd);
return "SUCCESS";
}
};
this.isUser = function(username) {
var users = new Array();
getAllUsers('param', function(response) {
users = response;
console.log(users.length);
for(i = 0; i < users.length; i++) {
if(users[i].username === username) {
return true;
}
}
return false;
});
};
function getAllUsers(param, callback) {
loginFactory.AllUsers.query(function(response) {
if(response != undefined && response.length > 0) {
callback(response);
}
});
}
You may rewrite the code like following:
this.doRegistration = function(uname, pwd, confirmPwd, callBack) {
this.isUser(uname,function(flag) {
if(flag){
callBack("USER_EXISTS");
}
else {
saveUser(uname, pwd, function(err,result){
if(err){
callBack("SAVING_FAILED");
}
else {
callBack("SUCCESS");
}
});
}
});
};
this.isUser = function(username,callBack) {
var users = new Array();
getAllUsers('param', function(response) {
users = response;
console.log(users.length);
for(i = 0; i < users.length; i++) {
if(users[i].username === username) {
callBack(true);
}
}
callBack(false);
});
};
function saveUser(userName, pwd, callBack){
//code to save user
//chek for error in saving
if(err){
callBack(err,null)
}
else {
callBack(null, "success")
}
}
function getAllUsers(param, callback) {
loginFactory.AllUsers.query(function(response) {
if(response != undefined && response.length > 0) {
callback(response);
}
});
}
You may also define saveUser as a function with callback. Here it wont wait for saveUser method to complete.

Resources