如何为promise的解析添加指定的延迟

时间:2013-10-21 15:24:15

标签: jquery promise

我想定义一个接受promise的函数,并返回一个相同的promise,除了返回的promises解析了一个任意的超时;我的代码看起来像下面的内容;但是我不确定我是否会像拒绝一样抓住所有东西。

//Returns a promise identical to promise, except with an additional delay
// specified by timeout.
delayedPromise(promise, timeout) {
    var newPromise = $.Deferred();
    promise.then(function(result) {
        window.setTimeout(function() {
            newPromise.resolve(result);
        }, 3000);
    }
    return newPromise;
}

有更好的方法吗?我是否还需要添加类似的函数来处理错误?

2 个答案:

答案 0 :(得分:2)

我认为你走在正确的轨道上,但是你错过了一些细节 - 特别是你的delayedPromise不会调用任何后续的回调,它们具有与原始承诺相同的上下文和参数。

试试这个,而不是:

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();
}

其中d.resolveWith()d.rejectWith调用是保留上述上下文和参数所必需的。

请注意,progress通知不会因此方法而延迟,但在此上下文中这些通知并不一定有意义。

同样,如果你真的希望被拒绝的承诺立即解决(没有延迟),那么删除传递给function的第二个.then

答案 1 :(得分:0)

我希望您能在Q中找到delay的实施情况。 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;
    });
};
相关问题