如何在承诺的解决方案中添加指定的延迟

如何在承诺的解决方案中添加指定的延迟

本文介绍了如何在承诺的解决方案中添加指定的延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个函数,该函数接受一个Promise,并返回相同的Promise,不同之处在于返回的Promise可以解决任意超时问题;我的代码如下所示;但我不确定是否会遇到拒绝之类的事情.

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 like below; but I'm not sure that I'm catching everything like rejection.

//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;
}

是否有更好的方法可以做到这一点?我还需要添加类似的功能来处理错误吗?

Is there a better way to do this? Do I also need to add a similar function to handle the errors?

推荐答案

我认为您处在正确的轨道上,但是您缺少一些详细信息-特别是您的delayedPromise不会使用与原始承诺相同的上下文和参数.

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.

尝试以下方法:

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调用对于保留上述上下文和参数是必需的.

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

请注意,尽管progress通知在这种情况下不一定有意义,但是使用此方法不会延迟通知.

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

类似地,如果您实际上希望被拒绝的诺言立即解决(没有延迟),则删除传递给.then的第二个function.

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

这篇关于如何在承诺的解决方案中添加指定的延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 21:11