在 Q 库中不使用“then"的链接承诺 [英] Chaining promises without using 'then' with Q library

查看:55
本文介绍了在 Q 库中不使用“then"的链接承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在没有then"的情况下链接 Q 承诺,所以最终这个链看起来像这样:

I'm trying to chain Q promises without 'then', so eventually the chain would look like this:

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

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

How to implement foo's methods so each one is executed once the promise of the previous one is resolved?

这个问题被标记为这个问题的完全重复,但我正在尝试使用 Q lib 而不是 jQuery 来实现.

This question was marked as exact duplicate of this one but I'm trying to implement this using Q lib, not jQuery.

推荐答案

我不确定您是否会因此而有所收获.

I'm not sure if you are going to gain anything with this.

我想你可以这样做:

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...
}

这篇关于在 Q 库中不使用“then"的链接承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆