in JavaScript, how to wrap a promise in timeout?

后端 未结 3 1760
清酒与你
清酒与你 2021-02-12 14:05

It\'s a common pattern to implement timeout of some asynchronous function, using deffered/promise:

// Create a Deferred and return its Promise
function timeout(f         


        
3条回答
  •  情话喂你
    2021-02-12 14:36

    function timeout(funct, args, time) {
        var deferred = new jQuery.Deferred(),
            promise = funct.apply(null, args);
    
        if (promise) {
            $.when(promise)
                .done(deferred.resolve)
                .fail(deferred.reject)
                .progress(deferred.notify);
        }
    
        setTimeout(function() {
            deferred.reject();
        }, time);
    
        return deferred.promise();
    }
    

提交回复
热议问题