Bluebird binding chain

I use Bluebird for promises and try to resolve the call chain, however using .bind () doesn't seem to work. I get:

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

The first method is called correctly and starts the promise chain, but I was not able to get the instance binding to work 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 last bluebird through:

npm install --save bluebird

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

+5
source share
1 answer

Throws this error because there is no testSecond on testFirst . If you want to do something after Promises resolves, follow these steps:

 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 they are resolved correctly, instead of executing console.log, return the line in the testFirst and testSecond and register 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, by running console.log in the spread callback, as shown below, it will write the lines returned by Promises above:

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

Source: https://habr.com/ru/post/1262553/


All Articles