如果您在使用 jQuery 1. 5 或以后, < a href=" http://api.jquery.com/cortion/ deferred-object/" rel="no follow" > Deferred 和 < a href="http://api.jquery.com/Types/#Promoise" rel=“nofollow" > Promise 是这类事情的朋友。您调用 AAAAX 调回什么是承诺物,您可以通过.done ()、.fail () 和.then () 附加函数。
然而,正如这个极好的推迟/承诺和所有这些东西(http://www.erichynds.com/jquery/using-deferreds-in-jquery/ )指出的,你还可以使用$.wait () 的能力来处理一个不承诺自动缓冲的价值。
$.when(getToken()).done(
function (token) {
// do something with the token, which may or may not have been
// retrieved from the remote service
}
);
既可以处理获取缓存值回来, 也可以处理没有问题的承诺 :
function getToken() {
// Return either the cached value or a jQuery Promise. If $.when() gets the
// cached value it will immediately realize that you didn t give it a
// promise and it will instead create a jQuery Deferred to return and
// .resolve() it using the value it did get. Thus, either way what
// comes out of the function is something .when() can deal with and call a function.
if (this.cache["token"]) {
return this.cache["token"];
} else {
return $.get(" ... some url ... ");
}
};