Reputation: 105
I am using Angular JS in salesforce visualforce page. I wrote this code to fetch some information from server. It is an asynchronous call.
var deferred = $q.defer();
Visualforce.remoting.Manager.invokeAction( //You can related this with any asynchronous service
'{!$RemoteAction.somepage.someMethod}',
param,
function(result,event){
if(event.type=='exception'){
deferred.reject(event.message);
}
else{
deferred.resolve(result);
}
}
);
return deferred.promise;
Now someone said to me that "Use promise instead of deferred" (but didn't explain why.) This code is working absolutely fine but it seems like some anti-pattern way of doing this (I'm not sure how but i read it somewhere.). Now i saw many documents and resources and tried to figure out what is the best approach to do this.
Can you please explain why it is not a good approach? Also how can i rewrite this code with best approach?
It would be really helpful if you provide your answers in simple language as i am quite new to Angular also i have been to many links so please don't throw more links to me. Thanks.
Edit 1:
I tried to implement the ES6 implementation but in the .then
function when i am simply updating a variable it is not running the digest cycle means changes are not reflecting on the UI but it working perfectly fine with my code and code provided by @smnbbrv. can you please provide why it is happening?
Upvotes: 0
Views: 845
Reputation: 124
I think its all down to massive bloated pieces of software trying to shave off loading times, using Promise.resolve()
limits your ability to use promises...compared to pushing them all into a promises array and then deferring that.
var service = {
getData:getData
}
return service;
function getData(){
getDataFromServerFunction
.$loaded()
.then(function (data){
deferred.resolve(data);
});
return deferred.promise;
}
Upvotes: 1
Reputation: 24541
I don't see anything bad in deferring (as long as this is kinda same promise in the end) however it is not a part of ES6 Promise standard / implementation. That's why at the moment you want to migrate from $q to native promises you won't be easily able to do so.
How to change your function: the very first example from here is fully applicable to your case
return $q(function(resolve, reject) {
Visualforce.remoting.Manager.invokeAction( //You can related this with any asynchronous service
'{!$RemoteAction.somepage.someMethod}',
param,
function(result,event){
if(event.type=='exception'){
reject(event.message);
}
else{
resolve(result);
}
}
);
Upvotes: 1