¿Alguien puede aclarar esta función de reducción de bluebird ... ¿Cómo funciona? Como usar esto ??
Quiero que esta función funcione como 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) { });Salida esperada: - Hardy Jack Danial
No usaría Promise.reduce , sino solo el método Array estándar:
[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); }); Pero realmente no tiene sentido usar una matriz tipo waterfall (¡literal!) de funciones con promesas. Solo escribe tu cadena:
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); });Como ahora estoy tan enamorado de async/await, quería agregar un complemento sobre cómo haría esto usándolo si su motor Javascript lo admite y/o si usa Babel o webpack para transpilar su fuente.
Si tiene 3 promesas, p1 , p2 y p3 , puede usar la siguiente sintaxis que es básicamente equivalente a async/waterfall excepto sin todas las funciones con devoluciones de llamada que se vuelven voluminosas rápidamente:
async function myAsyncAwaitWaterfallFunction() { try { const result1 = await p1 const result2 = await p2 const result3 = await p3 return `${result1}_${result2}_${result3}` } catch (e) { doSomethingWithAPromiseRejection(e) } }