i have piece of code, communicate ios native layer dispatching request callback id, , storing deferred
in array. when callback comes, can resolve or reject deferred
.
my code:
jsgate = (function () { function jsgate() {} jsgate._messagecount = 0; jsgate._callbackdeferreds = {}; jsgate.dispatch = function (plugin, method, args) { var callbackid, d, message; callbackid = this._messagecount; message = { plugin: plugin, method: method, "arguments": args, callbackid: callbackid }; send(message) this._messagecount++; d = new deferred; this._callbackdeferreds[callbackid] = d; return d.promise; }; jsgate.callback = function (callbackid, issuccess, valueorreason) { var d; d = this._callbackdeferreds[callbackid]; if (issuccess) { d.resolve(valueorreason[0]); } else { d.reject(valueorreason[0]); } return delete this._callbackdeferreds[callbackid]; }; return jsgate; })();
examples of usage:
jsgate.dispatch("readlater", "fetchsomething", []).then(function (value) { return console.log(value); }); return jsgate.dispatch("readlater", "asyncerror", []).then(function (value) { return console.log(value); }, function (reason) { return console.log("failed: " + reason); });
what's best practice using a+ promises?
after long research: there's no clean way of doing without strange hacks. main difference between deferred
, promise
can't manipulate promise
result outside. in general - it's approach, in specific case, need functionality, - have stick deferred
.
Comments
Post a Comment