I'm using Node.js and the Bluebird promises library.
This code works exactly the way I want:
/*
* Try using Bluebird promisify():
* - "Good" case: this works perfectly.
* ... but it DOESN'T use "promisify()"; it creates a new promise for each function.
* - SAMPLE OUTPUT:
* callABC()...
* a(): [ 'a' ]
* b(): [ 'a', 'b' ]
* c(): [ 'a', 'b', 'c' ]
* Done: results: [ 'a', 'b', 'c' ]
*/
var Promise = require('bluebird');
var a = function (results) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
results.push("a");
console.log("a(): ", results);
resolve(results);
}, 15);
});
}
var b = function (results) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
results.push("b");
console.log("b(): ", results);
resolve(results);
}, 5);
});
}
var c = function (results) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
results.push("c");
console.log("c(): ", results);
resolve(results);
}, 10);
});
}
var callABC = function (results) {
console.log("callABC()...");
a(results)
.then(b)
.then(c)
.then(function (results) {
console.log("Done: results:", results);
})
.catch(function (err) {
console.log("Error:", err);
});
}
callABC([]);
I understand that manually instantiating your own promises like this can be considered "bad":
Q: How can I "promisify" the above snippet?
I've tried many things; none of them have worked. For example:
/*
* Try using Bluebird promisify():
* - Fails: never calls b() or c()
*/
var Promise = require('bluebird');
var a = Promise.promisify(function (results) {
setTimeout(function() {
results.push("a");
console.log("a(): ", results);
}, 15);
});
var b = Promise.promisify(function (results) {
setTimeout(function() {
results.push("b");
console.log("b(): ", results);
}, 5);
});
var c = Promise.promisify(function (results) {
setTimeout(function() {
results.push("c");
console.log("c(): ", results);
}, 10);
});
var callABC = function (results) {
console.log("callABC()...");
a(results)
.then(b)
.then(c)
.then(function (results) {
console.log("Done: results:", results);
})
.catch(function (err) {
console.log("Error:", err);
});
}
callABC([]);
Q: What's the correct way to "promisify" the first example?
Q: In particular, how do I "resolve()" or "reject()" my callbacks if I substitute the automated Promise.promisify()
or Promise.promisifyAll()
for the manual new Promise()
? I imagine "throw" invokes .catch()
, but is there another (better?) mechanism?
Q: Are there any restrictions? For example, does the function need to have a callback parameter in order to be "promisified"?