javascript - One-time resolving promise singleton (Angular service) -
the question applies promises in general , isn't specific angular, example makes use of angular $q , service singletons.
here a plunker
var app = angular.module('app', []); app.factory('onetimeresolvingservice', function ($q) { var promise = $q(function(resolve, reject) { settimeout(function () { resolve(); }, 500); }); return promise; }); app.controller('acontroller', function (onetimeresolvingservice, $q) { onetimeresolvingservice.then(function () { console.log('a resolved'); return $q.reject(); }).then(function () { console.log('a resolved'); }); }); app.controller('bcontroller', function (onetimeresolvingservice, $q) { onetimeresolvingservice.then(function () { console.log('b resolved'); return $q.reject(); }).then(function () { console.log('b resolved'); }); });
and document is
<body ng-app="app"> <div ng-controller="acontroller"></div> <div ng-controller="bcontroller"></div> </body>
it naturally output
a resolved
b resolved
what pattern make singleton promise resolve first time, i.e.
a resolved
and not subsequent times?
something onetimeresolvingservice.$$state.status = 2
possibly can trick, looks $q hack , smells bad.
t.j. crowder correct in functionality you're looking in promise not exist. question of how achieve you're looking can found in structure below:
function onetimevalue($q) { var promisedvalue = $q(function(resolve, reject) { settimeout(function () {resolve('the 1 time value');}, 500); }); var valuegot = false; this.getvalue = function getvalue() { var res; if (!valuegot) { res = promisedvalue; } else { res = $q(function(resolve, reject) { resolve(null); }); } valuegot = true; return res; }; }
assuming new
once (as angular services do), getvalue() return promisified string upon first call. subsequent calls return null.
this plunker shows above in action
Comments
Post a Comment