我是一个客户端新手,试图围绕 jQuery Deferred 对象,特别是链接。我有一个 Promise 对象在其过滤工作中替换另一个 Promise 对象的情况:
// works great. output:
// about to resolve top layer
// top layer then results: {"id":"top_layer_deferred"}
// about to resolve second layer item 0
// top layer done: {"id":"second_layer_deferred"}
var top_layer_deferred = $.Deferred();
setTimeout(function() {
console.log('about to resolve top layer');
top_layer_deferred.resolve( { id: 'top_layer_deferred' } )
}, 10000 );
var top_layer_filter = top_layer_deferred.promise().then( function( results ) {
console.log('top layer then results: ' + JSON.stringify(results) );
var second_layer_deferred = $.Deferred();
setTimeout(function() {
console.log('about to resolve second layer item 0');
second_layer_deferred.resolve( { id: 'second_layer_deferred' } )
}, 2000 );
return second_layer_deferred.promise();
});
top_layer_filter.done( function(results) {
console.log('top layer done: ' + JSON.stringify(results) );
});
现在我想做同样的事情,但在过滤器代码中返回一个 promise 对象数组。(为了简单起见,我只是将一个 promise 对象放在数组上,而不使用任何参数来解析。)但是过滤器代码过早地触发,就好像它没有看到它的参数一样:
// doesn't work. output:
// about to resolve top layer
// top layer then results: {"id":"top_layer_deferred"}
// top layer done:
// about to resolve second layer item 0
var arr = [];
var top_layer_deferred = $.Deferred();
setTimeout(function() {
console.log('about to resolve top layer');
top_layer_deferred.resolve( { id: 'top_layer_deferred' } )
}, 10000 );
var top_layer_filter = top_layer_deferred.promise().then(function( results ) {
console.log('top layer then results: ' + JSON.stringify(results) );
var second_layer_deferred = $.Deferred();
setTimeout(function() {
console.log('about to resolve second layer item 0');
second_layer_deferred.resolve()
}, 2000 );
arr.push( second_layer_deferred.promise() );
return arr;
});
top_layer_filter.done( function() {
console.log('top layer done: ' );
});
我试过更换线路
top_layer_filter.done( function() {
和
$.when.apply(null,top_layer_filter).done( function() {
但这不会改变结果。
关于我所缺少的任何想法?
波莉