我有一个获取一些数据的函数,该函数应该返回一个 promise 。在函数中,我必须提出 2 个请求——一个接一个。我结束了一个嵌套的 deferrer 调用,其中函数将返回 deferrer 上的最后一次调用 resolves
。我对这种延迟的东西很陌生,想知道这是否是正确的解决方案。
function getData(func) {
var model = new Model();
var collection = new Collection();
var dfd = new jQuery.Deferred();
collection.fetch().then(function () {
model.fetch().then(function () {
dfd.resolve(collection);
});
});
return dfd.then(function (collection) {
return getViews(func(collection), model);
});
}
最佳答案
Andreas,我看到你已经完全正确地接受了 Vitaliy 的回答,我并不是想窃取他的观点,但以防万一你不知道,没有必要创建和解析你自己的 $.Deferred()
并且无需传递 collection
(func()
除外),因为它仍在范围内。
据我从问题中的代码可以看出,以下应该有效:
function getData(func) {
var collection = new Collection();
var model = new Model();
return $.when(collection.fetch(), model.fetch()).then(function() {
return getViews(func(collection), model);
});
}
关于javascript - 如何处理嵌套的 jquery 延迟调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17095023/