Closed azl397985856 closed 4 years ago
function reduceAsync(promises,initValue) {
return promises.reduce(function(promise,currentPromise){
return promise.then(currentPromise)
},Promise.resolve(initValue))
}
How about reduce?
Pretty straightforward, right?
function reduce(fn, initial = list[0], list) {
let acc = initial;
for (i in list) {
const item = list[i];
acc = fn(acc, item, i, list);
}
return acc;
}
reduce((acc, cur) => ((acc[cur] = cur), acc), {}, [1, 2, 3]);
then
to take out of the dataCause you can't create a promise and then immediately use its result synchronously in your code, you should call .then() on the promise, and the result will be there when the promise has been resolved.
The Code is a carbon copy of the reduce
listed above
function reduceAsync(fn, initial, promises) {
let accp = initial;
for (i in promises) {
const promise = promises[i];
accp = accp.then(acc => promise.then(v => fn(acc, v, i, promises)));
}
return accp;
}
reduceAsync((acc, cur) => ((acc[cur] = cur), acc), Promise.resolve({}), [
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3)
]).then(console.log);
Hope that make sense for U Guys~
Array.prototype.reduce是一个同步的方法,允许我们同步地进行操作。
如果我要实现异步reduce呢?
请实现以下函数: