【问题标题】:Chaining promises without using 'then' with Q library在 Q 库中不使用“then”链接承诺
【发布时间】:2017-04-06 10:43:33
【问题描述】:

我试图在没有“then”的情况下链接 Q Promise,因此最终链将如下所示:

var foo = new Foo();
foo
.method1()
.method2()
.method3();

如何实现 foo 的方法,以便在前一个的 Promise 解决后执行每个方法?

这个问题被标记为与this one 完全相同,但我正在尝试使用 Q lib,而不是 jQuery 来实现它。

【问题讨论】:

  • 在javascript中返回this关键字
  • 除非 Foo 是 Q 的扩展,否则this 并不能真正起作用。 method1 返回的东西本身必须包含一个 method2,它只有在 method1 解析后才调用自己。

标签: javascript promise q chaining


【解决方案1】:

我不确定你是否会从中获得任何好处。

我想你可以这样做:

function Foo() {
  var self = this,
      lastPromise = Promise.resolve();

  var chainPromise = function(method) {
    return function() {
      var args = Array.prototype.slice.call(arguments))
      lastPromise = lastPromise.then(function(){
        return method.apply(self, args);
      });
      return self;
    }
  }

  this.method1 = chainPromise(function() {
    // do the method1 stuff
    // return promise
  });

  this.method2 = chainPromise(function() {
    // do the method2 stuff
    // return promise
  });

  // etc...
}

【讨论】:

  • lastPromise = Promise.resolve()开头,避免分支
  • 如果你链接到lastPromise,你忽略了arguments
  • @zevane 谢谢!有用。但是为了得到之前promise的结果我修改了lastPromise,所以看起来像:lastPromise = lastPromise.then(function () { return method.apply(self, args.concat(Array.prototype.slice.call(arguments))); });
猜你喜欢
  • 2015-08-15
  • 2015-04-15
  • 1970-01-01
  • 2023-03-18
  • 2016-06-16
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
  • 2021-10-17
相关资源
最近更新 更多