可以通过蓝鸟的减法来解决依赖函数的数组吗?
任何人都可以澄清这个bluebird
减lessfunction…它是如何工作的? 如何使用这个?
我希望这个函数像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) { });
预期产出: 哈代Jack Danial
我不会使用Promise.reduce
,但只是标准的数组方法:
[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); });
但是,实际上,使用带有promise的waterfall
式数组(literal!)是没有意义的。 只要写出你的链条:
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); });
因为我现在非常喜欢asynchronous/等待,所以想要插入一个插件,如果你的Javascript引擎支持它,或者如果你使用Babel或者webpack来传输你的源代码,你将如何使用它。
如果你有3个promise, p1
, p2
和p3
,你可以使用下面的语法,基本上等同于async /
async function myAsyncAwaitWaterfallFunction() { try { const result1 = await p1 const result2 = await p2 const result3 = await p3 return `${result1}_${result2}_${result3}` } catch (e) { doSomethingWithAPromiseRejection(e) } }