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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With