使用jQuery.Deferred来避免嵌套的setTimeout回调

dav*_*ers 4 jquery promise coffeescript deferred

setTimeout ->
  console.log 'foo'
  setTimeout ->
    console.log 'bar'
    setTimeout ->
      console.log 'baz'
    , 1000
  , 1000
, 1000
Run Code Online (Sandbox Code Playgroud)

是否有可能用jQuery.Deferred实现相同的结果?或许如下:

someFunction()
.then(-> console.log 'foo')
.then(delay 1000)
.then(-> console.log 'bar')
.then(delay 1000)
.then(-> console.log 'baz')
Run Code Online (Sandbox Code Playgroud)

也许我错了,在思维的承诺可以很容易地写:做一个,然后一旦完成,做B超,然后一旦完成,可做C.

Ian*_*Ian 8

您可以.then()通过返回 Deferred对象来链接调用.特别是对于延迟,你可以使用类似的东西:

function someFunction() {
    var ret = new $.Deferred();
    // setTimeout just to simulate `someFunction` taking 1000ms to complete its deferred
    setTimeout(function () {
        ret.resolve();
    }, 1000);
    return ret;
}

function logger(str) {
    return function () {
        console.log("Logger:", str);
    };
}

function delay(time) {
    return function () {
        console.log("Delaying");
        var ret = new $.Deferred();
        setTimeout(function () {
            ret.resolve();
        }, time);
        return ret;
    };
}

someFunction()
    .then(logger("foo"))
    .then(delay(3000))
    .then(logger("bar"))
    .then(delay(3000))
    .then(logger("baz"));
Run Code Online (Sandbox Code Playgroud)

演示: http ://jsfiddle.net/yGcfu/