蓝鸟无极绑定链

Bluebird Promise Bind Chain

我将 Bluebird 用于 promises 并尝试允许链式调用,但是使用 .bind() 似乎不起作用。我得到:

TypeError: sample.testFirst(...).testSecond is not a function

第一个方法被正确调用并启动了承诺链,但我根本无法使实例绑定工作。

这是我的测试代码:

var Promise = require('bluebird');

SampleObject = function()
{
  this._ready = this.ready();
};

SampleObject.prototype.ready = function()
{
  return new Promise(function(resolve)
  {
    resolve();
  }).bind(this);
}

SampleObject.prototype.testFirst = function()
{
  return this._ready.then(function()
  {
    console.log('test_first');
  });
}

SampleObject.prototype.testSecond = function()
{
  return this._ready.then(function()
  {
    console.log('test_second');
  });
}

var sample = new SampleObject();
sample.testFirst().testSecond().then(function()
{
  console.log('done');
});

我正在通过以下方式使用最新的蓝鸟:

npm install --save bluebird

我是不是处理错了?我将不胜感激任何帮助。谢谢

它抛出这个错误是因为 testFirst 上没有方法 testSecond ,如果你想在两个 Promise 都解决后做某事,请像下面那样做:

var sample = new SampleObject();

Promise.join(sample.testFirst(), sample.testSecond()).spread(function (testFirst, testSecond){
  // Here testFirst is returned by resolving the promise created by `sample.testFirst` and 
  // testSecond is returned by resolving the promise created by `sample.testSecond`
});

如果您想检查两者是否都正确解析,而不是执行 console.log , return testFirsttestSecond 函数中的字符串并将它们登录spread 回调如下所示:

SampleObject.prototype.testFirst = function()
{
  return this._ready.then(function()
  {
    return 'test_first';
  });
}

SampleObject.prototype.testSecond = function()
{
  return this._ready.then(function()
  {
    return 'test_second';
  });
}

现在,如下所示在 spread 回调中执行 console.log,将记录由上述承诺编辑的 return 字符串:

Promise.join(sample.testFirst(), sample.testSecond()).spread(function(first, second){
  console.log(first); // test_first
  console.log(second); // test_second
});