Am I Returning This Promise Correctly?
I have a function, getMonitors inside a service. getMonitors returns a list of monitor objects. If the monitor object is empty, it grabs the monitors via http and stores the object
Solution 1:
Ah, I finally wrapped my head around promises. We can't return d.resolve(). That just sets a state. You always need to return d.promise and it if was resolved, it will return the resolve. Man. This drove me mad.I think I finally got the basic hang of promises after 3 different SO questions. I wish tutorials made this clearer. Everyone was only returning d.promise and no one really explained clearly that d.promise returns the state of the promise - which is changed by resolve or reject.
The correct code is:
getMonitors: function (forceReload) {
console.log ("** Inside ZMData getMonitors with forceReload="+forceReload);
var d = $q.defer();
if ((monitorsLoaded == 0) || (forceReload == 1)) // monitors are empty or force reload
{
console.log ("ZMDataModel: Invoking HTTP Factory to load monitors");
var apiurl = loginData.apiurl;
var myurl = apiurl+"/monitors.json";
$http.get(myurl)
.success(function(data)
{
// console.log ("HTTP success got " + JSON.stringify(data));
monitors = data.monitors;
console.log ("promise resolved inside HTTP success");
monitorsLoaded = 1;
d.resolve(monitors);
})
.error (function (err)
{
console.log ("HTTP Error " + err);
monitors = [];
console.log ("promise resolved inside HTTP fail");
d.resolve (monitors);
});
return d.promise;
}
else// monitors are loaded
{
console.log ("Returning pre-loaded list of "+monitors.length+" monitors");
d.resolve(monitors);
return d.promise;
}
}
Post a Comment for "Am I Returning This Promise Correctly?"