Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bluebird Promise Bind Chain

I am using Bluebird for promises and trying to allow chain calling however using .bind() doesnt seem to work. I am getting:

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

The first method is called correctly and starts the promise chain but I havent been able to get the instance binding working at all.

This is my test code:

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');
});

I am using the latest bluebird via:

npm install --save bluebird

Am I approaching this wrong? I would appreciate any help. Thanks.

like image 677
Pat841 Avatar asked Oct 30 '22 14:10

Pat841


1 Answers

It is throwing that error because, there is no method testSecond on testFirst , If you want to do something after both the Promises are resolved, do it like below :

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`
});

If you want to check if both are resolved properly, instead of doing a console.log , return the string in testFirst and testSecond functions and log them in the spread callback as shown below :

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

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

Now, doing a console.log in the spread callback as shown below , will log the strings returned by the promises above :

Promise.join(sample.testFirst(), sample.testSecond()).spread(function(first, second){
  console.log(first); // test_first
  console.log(second); // test_second
});
like image 171
Supradeep Avatar answered Nov 11 '22 21:11

Supradeep