我有一段代码,它通过调用具有回调ID的请求与iOS本机层进行通信,并在数组中存储Deferred
。然后,当回调发生时,我们可以解决或拒绝此Deferred
。
我的代码:
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;
})();
用法示例:
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);
});
使用A + Promises的最佳做法是什么?
答案 0 :(得分:0)
经过长时间的研究:没有奇怪的黑客攻击,没有干净的方法。 Deferred
和Promise
之间的主要区别在于我们无法操纵外部的Promise
结果。总的来说 - 这是一种很好的方法,但在这种特殊情况下,我们需要这种功能,所以 - 我们必须坚持使用Deferred
。