0

I've never used jQuery $.Deferred and so far I haven't found an example I can get my head around.

What I need is to be able to perform 3 separate tasks in order, step 1, step 2 and step 3. Step 2 should wait for step 1 to complete and step 3 should wait for step 2 to be complete before executing.

I'm trying the following but seem to be getting anywhere:

        var construct = new $.Deferred();

        construct.done(function() {
            console.log('Step 1');
        });

        construct.done(function() {
            setTimeout(5000);
            console.log('Step 2');
        });

        construct.done(function() {
            console.log('Step 3');
        });

        construct.resolve();

Does anyone have something simple working in a fiddle?

4

2 回答 2

2

为了Deferred像这样链接 s,你必须使用then,并返回一个新的Deferred

var construct = $.Deferred();

construct.then(function() {
    console.log('Step 1');
})
.then(function() {
    return $.Deferred(function (dfd) {
        setTimeout(function () {
            console.log('Step 2');
            dfd.resolve();
        }, 5000);
    });
})
.then(function() {
    console.log('Step 3');
});

construct.resolve();

这是小提琴:http: //jsfiddle.net/fMMsz/

于 2013-06-05T00:31:12.310 回答
0

我已经为异步操作写了一些类似的东西,但如果你想要它,你可以尝试这样的东西。我有一个setInterval模拟长时间运行的操作。

这背后的想法是Deferred为每个调用的函数返回一个对象,然后该对象将指示为定义的回调donefail(如果有的话)根据返回的结果采取行动。

JS小提琴

var loadQueue = function() {
    var dfrQueue1 = new $.Deferred();
    var i = 0;
    var loop = window.setInterval(function() {
      ++i;
      console.log('queue 1 - running: '+i);
      if (i >= 10) {
         // pass optional param to success callback
         dfrQueue1.resolve('queue 1'); 
         clearInterval(loop);
      }
    }, 1000);

    console.log('initiating queue 1');
    return dfrQueue1.promise();
};

var loadQueue2 = function() {
    var dfrQueue2 = new $.Deferred();
    var i = 0;
    var loop = window.setInterval(function() {
      ++i;
      console.log('queue 2 - running: '+i);
      if (i >= 5) {
          // pass optional param to success callback
          dfrQueue2.resolve('queue 2');
          clearInterval(loop);
      }
    }, 1000);

    console.log('initiating queue 2');
    return dfrQueue2.promise();
};

var t = loadQueue().done(loadQueue2);
于 2013-06-05T00:38:01.430 回答