带有自定义对象
function DeferredAjax(opts) { this.options=opts; this.deferred=$.Deferred(); this.country=opts.country;}DeferredAjax.prototype.invoke=function() { var self=this, data={country:self.country}; console.log("Making request for [" + self.country + "]"); return $.ajax({ type: "GET", url: "wait.php", data: data, dataType: "JSON", success: function(){ console.log("Successful request for [" + self.country + "]"); self.deferred.resolve(); } });};DeferredAjax.prototype.promise=function() { return this.deferred.promise();};var countries = ["US", "CA", "MX"], startingpoint = $.Deferred();startingpoint.resolve();$.each(countries, function(ix, country) { var da = new DeferredAjax({ country: country }); $.when(startingpoint ).then(function() { da.invoke(); }); startingpoint= da;});小提琴http://jsfiddle.net/7kuX9/1/
为了更清楚一点,可以写最后几行
c1=new DeferredAjax( {country:"US"} );c2=new DeferredAjax( {country:"CA"} );c3=new DeferredAjax( {country:"MX"} );$.when( c1 ).then( function() {c2.invoke();} );$.when( c2 ).then( function() {c3.invoke();} );带管道
function fireRequest(country) { return $.ajax({ type: "GET", url: "wait.php", data: {country:country}, dataType: "JSON", success: function(){ console.log("Successful request for [" + country + "]"); } });}var countries=["US","CA","MX"], startingpoint=$.Deferred();startingpoint.resolve();$.each(countries,function(ix,country) { startingpoint=startingpoint.pipe( function() { console.log("Making request for [" + country + "]"); return fireRequest(country); });});http://jsfiddle.net/k8aUj/1/
编辑:在结果窗口中输出日志的小提琴http://jsfiddle.net/k8aUj/3/
每个管道调用都返回一个新的Promise,该诺言又用于下一个管道。请注意,我仅提供了sccess功能,应该为失败提供类似的功能。
在每种解决方案中,通过将Ajax调用包装到一个函数中来延迟它们,直到需要使用为止,并为列表中的每个项目创建一个新的Promise以构建链。
我相信自定义对象提供了一种操作链的简便方法,但是管道可以更好地适合您的口味。
注意 :从jQuery
1.8开始,
deferred.pipe()不推荐使用,
deferred.then将其替换。



