使用jQuery.Deferred避免嵌套的setTimeout回调 [英] Using jQuery.Deferred to avoid nested setTimeout callbacks

查看:313
本文介绍了使用jQuery.Deferred避免嵌套的setTimeout回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

setTimeout ->
  console.log 'foo'
  setTimeout ->
    console.log 'bar'
    setTimeout ->
      console.log 'baz'
    , 1000
  , 1000
, 1000

是否可以使用jQuery.Deferred实现相同的结果?类似下面的东西:

Is it possible to achieve the same result with jQuery.Deferred? Something like the following, perhaps:

someFunction()
.then(-> console.log 'foo')
.then(delay 1000)
.then(-> console.log 'bar')
.then(delay 1000)
.then(-> console.log 'baz')

也许我错了思想承诺让写容易: > Do A,然后一旦完成,执行B,然后一旦完成,执行C 。

Perhaps I'm wrong in thinking promises make it easy to write: Do A, then once that finishes, do B, then once that finishes, do C.

推荐答案

可以通过返回 延迟对象来链接 .then()特别是对于延迟,你可以使用像:

You can chain the .then() calls by returning a new Deferred object. Specifically for delaying, you could use something like:

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"));

DEMO: http://jsfiddle.net/yGcfu/

这篇关于使用jQuery.Deferred避免嵌套的setTimeout回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆