javascript - Caching a promise object in AngularJS service -
javascript - Caching a promise object in AngularJS service -
i want implement dynamic loading of static resource in angularjs using promises. problem: have couple components on page might (or not, depends displayed, dynamic) need static resource server. 1 time loaded, can cached whole application life.
i have implemented mechanism, i'm new angular , promises, , want create sure if right solution \ approach.
var info = null; var deferredloaddata = null; function loaddatapromise() { if (deferredloaddata !== null) homecoming deferredloaddata.promise; deferredloaddata = $q.defer(); $http.get("data.json").then(function (res) { info = res.data; homecoming deferredloaddata.resolve(); }, function (res) { homecoming deferredloaddata.reject(); }); homecoming deferredloaddata.promise; }
so, 1 request made, , next calls loaddatapromise() first made promise. seems work request in progress or 1 finished time ago.
but solution cache promises?
is right approach?
yes. utilize of memoisation on functions homecoming promises mutual technique avoid repeated execution of asynchronous (and expensive) tasks. promise makes caching easy because 1 not need distinguish between ongoing , finished operations, they're both represented (the same) promise result value.
is right solution?
no. global data
variable , resolution undefined
not how promises intended work. instead, fulfill promise result data
! makes coding lot easier:
var datapromise = null; function getdata() { if (datapromise == null) datapromise = $http.get("data.json").then(function (res) { homecoming res.data; }); homecoming datapromise; }
then, instead of loaddatapromise().then(function() { /* utilize global */ info })
getdata().then(function(data) { … })
.
to farther improve pattern, might want hide datapromise
in closure scope, , notice need lookup different promises when getdata
takes parameter (like url).
javascript angularjs promise angular-promise
Comments
Post a Comment