๋ฌธ์ )
Given an array of asynchronous functions functions, return a new promise promise. Each function in the array accepts no arguments and returns a promise.
promise resolves:
- When all the promises returned from functions were resolved successfully. The resolved value of promise should be an array of all the resolved values of promises in the same order as they were in the functions.
promise rejects:
- When any of the promises returned from functions were rejected. promise should also reject with the reason of the first rejection.
Please solve it without using the built-in Promise.all function.
๊ฐ๋จํ๊ฒ ์์ฝํด๋ณด์๋ฉด,
- ๋น๋๊ธฐ ํจ์ ๋ฐฐ์ด functions๋ฅผ ์คฌ์ ๋, ์๋ก์ด promise๋ฅผ ๋ฐํํ์์ค.
- functions์์ ๋ฐํ๋ ํ๋ก๋ฏธ์ค ์ค์ ์ด๋ ํ๋๋ผ๋ ๊ฑฐ๋ถ๋๋ฉด, promise๋ ๊ฑฐ๋ถ๋ฉ๋๋ค.
ํด๊ฒฐ)
var promiseAll = async function(functions) {
return new Promise((resolve,reject)=>{
let ans=[],j=functions.length;
functions.forEach((func,i)=>{
func().then((res)=>{
(ans[i]=res,--j===0 && resolve(ans))
})
.catch(reject)
})
})
};
- Promise.all() ์ ์ฌ์ฉํ์ ๋
var promiseAll = async function(functions) {
const results = Promise.all(functions.map(func => func()));
return results;
};
Promise.all()์ด๋?
Promise.all()์ ์ํ๊ฐ๋ฅํ ๊ฐ์ฒด์ ์ฃผ์ด์ง ๋ชจ๋ ํ๋ก๋ฏธ์ค๋ฅผ ์ดํํ ํ์ ํน์ ํ๋ก๋ฏธ์ค๊ฐ ์ฃผ์ด์ง์ง ์์์ ๋ ์ดํํ๋ ํ๋ก๋ฏธ์ค๋ฅผ ๋ฐํํฉ๋๋ค. ์ฃผ์ด์ง ํ๋ก๋ฏธ์ค ์ค ํ๋๊ฐ ๊ฑฐ๋ถํ๋ ๊ฒฝ์ฐ, ์ฒซ๋ฒ์งธ๋ก ๊ฑฐ์ ํ ํ๋ก๋ฏธ์ค์ ์ด์ ๋ฅผ ์ฌ์ฉํด ์์ ๋ ๊ฑฐ๋ถํฉ๋๋ค. ์ฌ๋ฌ ๊ฐ์ ํ๋ก๋ฏธ์ค๋ฅผ ๋น๋๊ธฐ์ ์ผ๋ก ์คํํ๊ธฐ ๋๋ฌธ์ ์ฌ๋ฌ๊ฐ์ promise ์ฒ๋ฆฌ๋ฅผ ๋น๋๊ธฐ์ ์ผ๋ก ํ๊ณ ์ ํ ๋ ์ฌ์ฉํ ์ ์์ต๋๋ค.
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'foo');
});
Promise.all([promise1, promise2, promise3]).then((values) => {
console.log(values);
});
// Expected output: Array [3, 42, "foo"]
'๊ฐ๋ฐ > ๐ฌ ์ฝ๋ฉํ ์คํธ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[leetCode/EASY] 1431. Kids With the Greatest Number of Candies (0) | 2024.01.17 |
---|---|
[leetCode] 34. Find First and Last Position of Element in Sorted Array - Javascript (0) | 2023.11.10 |
[leeCode/์ฝํ ๊ณต๋ถ] 2625. Flatten Deeply Nested Array (0) | 2023.08.21 |
[์๊ณ ๋ฆฌ์ฆ] .val ๊ณผ .next ์ ๋ป์? (0) | 2022.12.30 |
[codewars] Valid Parentheses (0) | 2022.03.30 |