์ฌ๋ฌ ๋น๋๊ธฐ ํจ์์์ ๋ฐํ๋๋ ๋ฐ์ดํฐ๋ฅผ ๋ณํฉํ๊ณ id ๊ธฐ์ค์ผ๋ก ์ ๋ ฌํ๋ ๋ฌธ์
// ํจ์ A ๋ฐํ๊ฐ: [{ id:1, name:'Alice'}, { id:2, age:20 }]
// ํจ์ B ๋ฐํ๊ฐ: [{ id:1, age:25 }, { id:3, gender:'F'}]
// ๊ฒฐ๊ณผ:
[
{ id:1, name:'Alice', age:25 },
{ id:2, age:20 },
{ id:3, gender:'F'}
]
๋น๋๊ธฐ ํจ์ ๋ฐฐ์ด์ ์คํ ์์ ์ดํด
Promise.all๊ณผ ๋ฐฐ์ด ์ฒ๋ฆฌ
๋ฐ์ดํฐ ๋ณํฉ ์ ๋ต
async function asyncDataMerger(...asyncFunctions) {
const combineArr = (
await Promise.all(asyncFunctions.map((func) => func()))
).flat();
return combineArr
.reduce((a, c) => {
const curIdx = a.findIndex((e) => c.id === e.id);
if (curIdx !== -1) {
a[curIdx] = { ...a[curIdx], ...c };
} else {
a.push(c);
}
return a;
}, [])
.sort((a, b) => a.id - b.id);
}
const asyncFunctions = [
async () => [...], // ์์ง ์คํ๋์ง ์์ ํจ์
async () => [...], // ์์ง ์คํ๋์ง ์์ ํจ์
];
asyncFunctions.map(fn => fn()) // ๊ฐ ํจ์๋ฅผ ์คํํ์ฌ Promise ๋ฐํ
// Promise.all์ ๊ฒฐ๊ณผ (๋ฐฐ์ด์ ๋ฐฐ์ด)
[
[{ id: 1, name: 'Alice' }, { id: 2, age: 20 }],
[{ id: 1, age: 25 }, { id: 3, gender: 'F' }]
]
// flat() ์ ์ฉ ํ (1์ฐจ์ ๋ฐฐ์ด)
[
{ id: 1, name: 'Alice' },
{ id: 2, age: 20 },
{ id: 1, age: 25 },
{ id: 3, gender: 'F' }
]
.reduce((a, c) => {
const curIdx = a.findIndex((e) => c.id === e.id);
if (curIdx !== -1) {
a[curIdx] = { ...a[curIdx], ...c }; // ๊ฐ์ฒด ๋ณํฉ
} else {
a.push(c); // ์๋ก์ด id๋ ์ถ๊ฐ
}
return a;
}, [])
async/await์ Promise์ ๊ด๊ณ
map๊ณผ Promise.all์ ํ๋ ฅ
flat์ ์ ์ฉ์ฑ