5
我见过,看起来像这样的代码几位近期:添加一个方法,然后给一个函数回调
myFunc(args).then(function() { ... });
我觉得这句法回调真的优雅。我的理解是,这不是vanilla JS的一部分,我希望能够偶尔使用它,而不依赖于特定的库,所以我对如何自己实现这一点感兴趣。那么,这种事情是如何工作的,以及如何为函数调用实现它?
我见过,看起来像这样的代码几位近期:添加一个方法,然后给一个函数回调
myFunc(args).then(function() { ... });
我觉得这句法回调真的优雅。我的理解是,这不是vanilla JS的一部分,我希望能够偶尔使用它,而不依赖于特定的库,所以我对如何自己实现这一点感兴趣。那么,这种事情是如何工作的,以及如何为函数调用实现它?
这种模式被称为“承诺”。它通过jQuery和dojo等实现,一种方法是查看它们的代码并查看它们是如何实现的。
一般实现模式是创建一个函数,该函数返回一个对象,该对象包含一个函数(然后)将一对函数作为回调函数传递给先前的方法,然后在成功或失败时运行该方法。 MSDN有更多关于在blog post here
承诺有张贴在Github上这里极简实现:Promises GIST
function Promise() {
this._thens = [];
}
Promise.prototype = {
/* This is the "front end" API. */
// then(onResolve, onReject): Code waiting for this promise uses the
// then() method to be notified when the promise is complete. There
// are two completion callbacks: onReject and onResolve. A more
// robust promise implementation will also have an onProgress handler.
then: function (onResolve, onReject) {
// capture calls to then()
this._thens.push({ resolve: onResolve, reject: onReject });
},
// Some promise implementations also have a cancel() front end API that
// calls all of the onReject() callbacks (aka a "cancelable promise").
// cancel: function (reason) {},
/* This is the "back end" API. */
// resolve(resolvedValue): The resolve() method is called when a promise
// is resolved (duh). The resolved value (if any) is passed by the resolver
// to this method. All waiting onResolve callbacks are called
// and any future ones are, too, each being passed the resolved value.
resolve: function (val) { this._complete('resolve', val); },
// reject(exception): The reject() method is called when a promise cannot
// be resolved. Typically, you'd pass an exception as the single parameter,
// but any other argument, including none at all, is acceptable.
// All waiting and all future onReject callbacks are called when reject()
// is called and are passed the exception parameter.
reject: function (ex) { this._complete('reject', ex); },
// Some promises may have a progress handler. The back end API to signal a
// progress "event" has a single parameter. The contents of this parameter
// could be just about anything and is specific to your implementation.
// progress: function (data) {},
/* "Private" methods. */
_complete: function (which, arg) {
// switch over to sync then()
this.then = which === 'resolve' ?
function (resolve, reject) { resolve(arg); } :
function (resolve, reject) { reject(arg); };
// disallow multiple calls to resolve or reject
this.resolve = this.reject =
function() { throw new Error('Promise already completed.'); };
// complete all waiting (async) then()s
var aThen, i = 0;
while (aThen = this._thens[i++]) { aThen[which] && aThen[which](arg); }
delete this._thens;
}
};
(请注意,这不是我的代码,通过它看上去和它看起来不错的起点。 ,但所有功劳都归功于original author)
'then'方法往往是“承诺”模式的一部分。 jQuery将其实现为“延迟”api的一部分。 – zzzzBov 2013-02-10 01:55:00
[道格拉斯克罗克福德在他的“Monads和Gonads”谈话中简单地接触了诺言](http://www.youtube.com/watch?v=dkZFtimgAcM&t=1920) – zzzzBov 2013-02-10 01:58:05
阅读关于CommonJS承诺建议,其中还包括一个库列表你可以使用:http://wiki.commonjs.org/wiki/Promises/A。 – 2013-02-10 03:32:39