Can anyone please clarify this reduce function of bluebird ...
How it works ? How to use this ??
I want this function work like async.waterfall([ARRAY OF FUNCTIONS])
"use strict";
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
Promise.reduce([function() {
return 'Hardy';
}, function(name) {
console.log('0000' + name);
return name + ' Jack';
}, function(fullName) {
console.log('000011' + fullName);
return fullName + ' Danial';
}],
function(total, data) {
console.log(total);
console.log(data);
}, 0).then(function(total) {
});
Expected Output :- Hardy Jack Danial
I would not use Promise.reduce, but just the standard Array method:
[function() {
return 'Hardy';
}, function(name) {
console.log('0000' + name);
return name + ' Jack';
}, function(fullName) {
console.log('000011' + fullName);
return fullName + ' Danial';
}].reduce(function(promise, fn) {
return promise.then(fn);
}, Promise.resolve()).then(function(total) {
console.log(total);
});
But really there's no point in using a waterfall-like array (literal!) of functions with promises. Just write out your chain:
Promise.resolve().then(function() {
return 'Hardy';
}).then(function(name) {
console.log('0000' + name);
return name + ' Jack';
}).then(function(fullName) {
console.log('000011' + fullName);
return fullName + ' Danial';
}).then(function(total) {
console.log(total);
});
Since I'm so in love with async/await now, wanted to throw in a plug for how you would do this using it if your Javascript engine supports it and/or if you use Babel or webpack to transpile your source.
If you have 3 promises, p1, p2, and p3, you can use the following syntax which is basically equivalent to async/waterfall except without all the functions with callbacks that gets bulky quick:
async function myAsyncAwaitWaterfallFunction() {
try {
const result1 = await p1
const result2 = await p2
const result3 = await p3
return `${result1}_${result2}_${result3}`
} catch (e) {
doSomethingWithAPromiseRejection(e)
}
}