ํฐ์คํ ๋ฆฌ ๋ทฐ
ํ๋์ async function ๋ด์์๋ await
ํค์๋๋ฅผ ๋ง๋ ๋๋ง๋ค
๋ง ๊ทธ๋๋ก ๊ธฐ๋ค๋ ธ๋ค๊ฐ(await) ๋น๋๊ธฐ์ฒ๋ฆฌ๊ฐ ์๋ฃ ๋ ํ ์ง๋ ฌ๋ก ๋ค์ task๋ฅผ ์ฒ๋ฆฌํ๋ค.
๋ง์ฝ์ async ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ๊ตฌํํ๋ ๊ณผ์ ์ค์ each
๋ times
์ฒ๋ผ
์ฌ๋ฌ ๋น๋๊ธฐ task๋ฅผ ๋ณ๋ ฌ์ ์ผ๋ก ์์์ํค๋ ค๋ฉด ์ด๋ป๊ฒ ํด์ผํ ๊น?
๋ง์ฝ Promise.all
๊ฐ ๋ณ๋ ฌ๋ก ๋์ํ๋ค๋ฉด ์๊ฑธ ์ฐ๋ฉด ๋ ๊ฒ ๊ฐ๋ค!!
๊ทธ๋์ ํ๋ฒ ํ์ธํด๋ณด์๋ค.
โ
async/await ์ง๋ ฌ์ฒ๋ฆฌ
function nSecondsLater(n) {
console.log(`๐ฉ n=${n} Start`);
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`โ
${n} Seconds Later`);
}, n * 1000);
});
}
const arr = [0, 1, 2, 3]
async function asyncWaterfall() {
for (let n of arr) {
const promise = await nSecondsLater(n);
console.log(promise);
}
console.log("DONE!");
}
asyncWaterfall();
async/await
: for of
๋ฌธ์ ์ฌ์ฉํ์ฌ ์ํ ํ ๊ฒฝ์ฐ
์๋์ ๊ฐ์ด waterfall ํํ๋ก ์คํ๋๋ค.
โ
Promise.all()์ ์ด์ฉํ ๋ณ๋ ฌ์ฒ๋ฆฌ
function asyncParallel() {
const promises = arr.map(n =>
nSecondsLater(n).then(console.log)
);
Promise.all(promises).then(() => console.log("DONE!"));
}
asyncParallel();
์์ ๊ฐ์ด Promise.all()
์ ์ด์ฉํ์ฌ ํ๋ฒ์ ์ฒ๋ฆฌํ ๊ฒฝ์ฐ
์๋์ ๊ฐ์ด ์ํ๋ ๋๋ก ๋ณ๋ ฌ๋ก ๋์ํ๋ค!
โ
์ถ๊ฐ!
+ async/await
์์ด waterfall ๊ตฌํํ๊ธฐ
function asyncWaterfall2() {
const promise = arr.reduce((accPromise, n) => {
return accPromise.then(() => {
return nSecondsLater(n).then(console.log);
});
}, Promise.resolve());
promise.then(() => console.log("DONE!"));
}
asyncWaterfall2();
์ฌ์ ํ ์์ง์ ๋น๋๊ธฐ ๋ฌธ๋ฒ๋ค์ด ์ต์์น ์์ง๋ง ์ฌ๋ฌ๊ฐ์ง ์์ ์ฝ๋๋ฅผ ์์ฃผ ์ง๋ด์ผ๊ฒ ๋น
'๊ณต๋ถ > JS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JS/์๊ณ ๋ฆฌ์ฆ] Find First and Last Position of Element in Sorted Array (0) | 2020.09.07 |
---|---|
[JS/์๊ณ ๋ฆฌ์ฆ] Merge Two Sorted Lists (0) | 2020.09.07 |
[JS] Prevent Stack Overflow (0) | 2020.08.06 |
[JS] #๋ชจ์๊ณ ์ฌ - ํ๋ก๊ทธ๋๋จธ์ค ์ฝ๋ฉํ ์คํธ ์ฐ์ต (0) | 2020.07.12 |
[JS] N๊ฐ์ length ๋ฅผ ๊ฐ์ง array์ ๊ฐ ์ฑ์ฐ๊ธฐ (0) | 2020.07.12 |
- eslint
- DOM
- stackoverflow
- KEYBOARD
- book
- Stash
- review
- js
- ๋ถํธ์บ ํ
- eventlistener
- ์ฝ๋ฉ๋ถํธ์บ ํ
- css
- ๋ฐ๋๋ผ์ฝ๋ฉ
- GIT
- VSC
- array
- string
- HTML
- ๋ฐ๋๋ผ์ฝ๋ฉ ํ๊ธฐ
- ์์ฑ์ํจ์
- Total
- Today
- Yesterday