map과 reduce에서 async await 사용하기

오픈소스·2023년 3월 15일
0
post-thumbnail
post-custom-banner
  • map
    • Promise.all()
const promiseMessages = await Promise.all(
  names.map(async (name) => await sayHello(name)),
)
  • reduce
    • Promise.resolve()
    • await promise
const oddMessages = await names.reduce(async (prev, current, index) => {
  const prevResult = await prev.then()
  if (index % 2 === 0) {
    const result = await sayHello(current)
    return Promise.resolve([...prevResult, result])
  } else {
    return Promise.resolve(prevResult)
  }
}, Promise.resolve([]))
const messageObject = await arr.reduce(async (promise, user) => {
    let result = await promise;
    result[user.id] = await getIntroMessage(user);
    return result;
}, {});
return Object.values(groups)
	.reduce(async (memo, group) => [
		...(await memo),
		...(await Promise.all(group.map(iteratee)))
	], []);
const arr = [1, 2, 3, 4, 5];

const sum = async () => {
  return arr.reduce(async (accumulatorPromise: Promise<number>, currentValue: number) => {
    const accumulator = await accumulatorPromise;
    return accumulator + currentValue;
  }, Promise.resolve(0));
};

sum().then(result => {
  console.log(result); // 15
});

참고)

post-custom-banner

0개의 댓글