首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在JavaScript中,如何在超时中包装承诺?

在JavaScript中,如何在超时中包装承诺?
EN

Stack Overflow用户
提问于 2014-06-12 19:42:58
回答 2查看 10.3K关注 0票数 20

实现某些异步函数超时是一种常见模式,使用deffered/promise:

代码语言:javascript
复制
// Create a Deferred and return its Promise
function timeout(funct, args, time) {
    var dfd = new jQuery.Deferred();

    // execute asynchronous code
    funct.apply(null, args);

    // When the asynchronous code is completed, resolve the Deferred:
    dfd.resolve('success');

    setTimeout(function() {
        dfd.reject('sorry');
    }, time);
    return dfd.promise();
}

现在我们可以执行一些名为myFunc的异步函数并处理超时:

代码语言:javascript
复制
// Attach a done and fail handler for the asyncEvent
$.when( timeout(myFunc, [some_args], 1000) ).then(
    function(status) {
        alert( status + ', things are going well' );
    },
    function(status) {
        alert( status + ', you fail this time' );
    }
);

好了,让我们在这个故事中来个转折吧!假设myFunc本身返回一个promise (注意: promise没有延迟,我不能更改它):

代码语言:javascript
复制
function myFunc(){
    var dfd = new jQuery.Deffered();
    superImportantLibrary.doSomething(function(data)){
       if(data.length < 5){
            dfd.reject('too few data');
       }
       else{
           dfd.resolve('success!');
       }
    }, {'error_callback': function(){
        dfd.reject("there was something wrong but it wasn't timeout");}
    }});
    return dfd.promise();
}

现在,如果我将myFunc包装在timeout中,我将失去处理不同于超时的错误的能力。如果myFunc发出进度事件,我也会丢失它。

所以问题是:如何修改timeout函数,以便它可以接受返回承诺的函数,而不会丢失它们的错误/进度信息?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24183480

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档