【问题标题】:How do I add a specified delay to the resolution of a promise如何在承诺的解决中添加指定的延迟
【发布时间】:2013-10-22 17:11:16
【问题描述】:

我想定义一个函数,它接受一个 Promise,并返回一个相同的 Promise,除了返回的 Promise 解决了任意超时;我的代码如下所示;但我不确定我是否理解了拒绝之类的一切。

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

有没有更好的方法来做到这一点?我是否还需要添加类似的函数来处理错误?

【问题讨论】:

    标签: jquery promise


    【解决方案1】:

    我认为您在正确的轨道上,但是您遗漏了一些细节 - 特别是您的 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 通知,尽管在这种情况下这些通知不一定有意义。

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

    【讨论】:

      【解决方案2】:

      希望你在 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;
          });
      };
      

      【讨论】:

      • 此实现与 OP 的原始代码存在相同的问题 - 在解析延迟回调时,它不会保留 this 或传递的整组参数。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-23
      • 2015-03-29
      • 2016-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多