How do I add a specified delay to the resolution of a promise

前端 未结 2 569
傲寒
傲寒 2021-01-24 12:22

I\'d like to define a function that takes a promise, and returns an identical promise, except that the returned promises resolves an arbitrary timeout; my code looks something l

相关标签:
2条回答
  • 2021-01-24 12:49

    I hope you find the implementation of delay in Q insightful. https://github.com/kriskowal/q/blob/master/q.js#L1629-L1637

    Q.delay = function (object, timeout) {
        if (timeout === void 0) {
            timeout = object;
            object = void 0;
        }
        return Q(object).delay(timeout);
    };
    
    Promise.prototype.delay = function (timeout) {
        return this.then(function (value) {
            var deferred = defer();
            setTimeout(function () {
                deferred.resolve(value);
            }, timeout);
            return deferred.promise;
        });
    };
    
    0 讨论(0)
  • 2021-01-24 13:02

    I think you're on the right track, but that you're missing some details - specifically your delayedPromise won't invoke any subsequent callbacks with the same context and parameters as the original promise.

    Try this, instead:

    function delayedPromise(promise, timeout) {
        var d = $.Deferred();
    
        promise.then(function () {
            var ctx = this;
            var args = [].slice.call(arguments, 0);
            setTimeout(function () {
                d.resolveWith(ctx, args);
            }, timeout);
        }, function () {
            var ctx = this;
            var args = [].slice.call(arguments, 0);
            setTimeout(function () {
                d.rejectWith(ctx, args);
            }, timeout);
        });
    
        return d.promise();
    }
    

    where the d.resolveWith() and d.rejectWith calls are necessary to preserve the aforementioned context and parameters.

    Note that you progress notifications are not delayed with this method, although those don't necessarily make any sense in this context.

    Similarly, if you actually want rejected promises to resolve immediately (without delay) then remove the second function passed to .then.

    0 讨论(0)
提交回复
热议问题