【问题标题】:jquery step by step with $.Deferred() [duplicate]jquery 一步一步用 $.Deferred() [重复]
【发布时间】:2015-09-23 13:25:51
【问题描述】:

这里是测试代码:

var dfd_1 = $.Deferred(),
    dfd_2 = $.Deferred(),
    dfd_3 = $.Deferred();

function test(content, waitTime, dfd) {
    console.log(content + ' begin');
    setTimeout(function() {
        console.log(content + ' end');
        dfd.resolve();
    }, waitTime);
    return dfd.promise();
}

$.when(test('first', 2000, dfd_1), test('second', 4000, dfd_2), test('third', 6000, dfd_3))
.then(function() {
    console.log('all done');
});

控制台的结果是:

first begin 
second begin
third begin

first end
second end
third end

all done

3 函数开始后逐步结束 但我需要这样的结果(开始结束,开始结束......):

first begin
first end

second begin
second end

third begin
third end

all done

如何逐步使$.Deferred 工作? 请帮我解决一下

【问题讨论】:

  • 你想排队执行吗?
  • @dev-null 是的,first start first end, second start - second end 但没有回调,如何使用 Deferred 来实现

标签: javascript jquery


【解决方案1】:

使用then():

test('first', 2000, dfd_1)
    .then(function() {
        return test('second', 4000, dfd_2);
    })
    .then(function() {
        return test('third', 6000, dfd_3);
    })
    .then(function() {
        console.log('all done');
    })
;

小提琴:http://jsfiddle.net/saj5stt9/

【讨论】:

  • 但这不允许同时调用,而正确使用$.when 可以。 jsfiddle.net/dr3w9byk
  • OP 特别需要串行执行“如何逐步使 $.Deferred 工作?”。如果 Promise 依赖于先前调用的结果,这是一个有效的用例。
  • 好的...我解释为需要按顺序排列的结果,因为这是在$.when中设置的方式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多