reduce方法可以簡化非同步函式的序列與並行寫法
function log(n, delay, param) {
return function () {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(n);
resolve(param);
}, delay);
})
}
}
Promise.all([
log(1, 300, "aa")(), log(2, 0, "bb")(), log(3, 1500, "cc")(), log(4, 100, "dd")()
]).then((result) => {
console.log('finished!')
console.log(result);
});
列印:2、4、1、3
[log(1, 300),log(2, 0),log(3, 500),log(4, 100)].reduce((accumulator, value) => {
return accumulator.then(value)
},Promise.resolve());
列印: 1、2、3、4
複製程式碼
可以使用Array.reduce()將多維陣列拍平
var array = [1, [2, [3, 4], 5], 6];
function flatten(array) {
return array.reduce(function (arr, item) {
return (Object.prototype.toString.call(item) === '[object Array]'
? Array.prototype.push.apply(arr, flatten(item))
: arr.push(item)
, arr);
}, []);
}
console.log(flatten(array));複製程式碼