Using "bluebird": "^3.4.6" :
var Promise = require('bluebird');
Promise.config({
warnings: true,
longStackTraces: true,
cancellation: true,
monitoring: true
});
function getPromise1(param1, param2) {
return new Promise( (resolve, reject) => {
console.log(param1, param2);
resolve();
} );
}
function getPromise2(param1, param2) {
return new Promise( (resolve, reject) => {
console.log(param1, param2);
resolve();
} );
}
function mainFunc(param1, param2) {
getPromise1(param1, param2)
.then(getPromise2(param1, param2));
}
mainFunc("param1", "param2");
When I run it, I get :
$ node index.js
param1 param2
param1 param2
(node:95984) Warning: .then() only accepts functions but was passed: [object Object]
How can I modify this piece of code to do the same thing without the warning? Is this warning pertinent or is it just a heads-up for the developer?
EDIT: Yes. I understand the text of the warning, i.e. .then expects a function when it actually gets a Promise object from the getPromise2 function. Nevertheless, the promise gets called. (helpful downvotes)
My predicament is how to chain promises in such a way that a new Promise will be called in the then function after the first promise executes.
The getPromise2() call immediately creates the promise; it then is ignored being passed to then instead of a callback. To actually chain them, you'd need to use
function mainFunc(param1, param2) {
return getPromise1(param1, param2).then(function(promise1result) {
return getPromise2(param1, param2);
});
}
The key is that you have to pass a function to .then(). You were executing your function immediately and passing the returned result from that function (which was a promise). So, you can create your own anonymous wrapper function as in Bergi's answer or you can use .bind() as in:
function mainFunc(param1, param2) {
return getPromise1(param1, param2).then(getPromise2.bind(null, param1, param2));
}
.bind() creates the wrapper function for you and allows you to specify the arguments you want preprended to the argument list when the function is actually called at a later time.
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