【问题标题】:dojo.Deferred: Gracefully canceling a .then() chain?dojo.Deferred:优雅地取消 .then() 链?
【发布时间】:2011-03-29 13:26:57
【问题描述】:

我有一个异步调用链,使用 dojo.Deferred 对象作为异步包装器链接在一起(至少我是这么理解的)和 .then() 函数来“链接”异步调用。

在链中的任何一个链接中,某些测试可能会失败(例如我的异步存储提取未返回任何对象等),我想优雅地退出整个 .then() 链。

这是我使用的链的形式。我如何杀死我指出的整个链条?

asyncFunc(...).then( function(args) {
    //stuff...
    return myDeferredReturningFunction(args);
}).then( function(args2) {
    //do some test on args2
    //if test fails, **how to cancel the chain here?**
}).then( function(args3) { ... etc etc ...

注意:也许有人可以将其标记为“dojo.Deferred”?

【问题讨论】:

    标签: asynchronous dojo


    【解决方案1】:

    抛出异常应该是一种简单的解决方法,因为它会跳出任何回调并进入任何补充或后续的错误返回。

    快速示例:

    dojo.xhrGet({url:'base.php'})
        .then(function() { console.log('foo'); throw 'argh!';})
        .then(function() { console.log('bar'); }); // bar never gets printed
    

    更多信息:

    http://www.sitepen.com/blog/2009/03/31/queued-demystifying-deferreds/

    http://www.sitepen.com/blog/2010/05/03/robust-promises-with-dojo-deferred-1-5/

    【讨论】:

    • 我在 Dojo 1.8 中试过这个。如果 then() 上有 errBacks,则 throw 不会取消链。错误回调将被执行。似乎没有办法在 then 链中真正引发异常。这个封闭的缺陷似乎表明了这一点:bugs.dojotoolkit.org/ticket/3814
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    • 2012-09-19
    相关资源
    最近更新 更多