๐ async & await๋ ๋น๋๊ธฐ ์ฒ๋ฆฌ ํจํด์ผ๋ก, ๊ธฐ์กด์ ์ฝ๋ฐฑํจ์์ ํ๋ก๋ฏธ์ค์ ๋จ์ ์ ๋ณด์ํ ๋ฌธ๋ฒ์
๋๋ค. ์๋ฐ์คํฌ๋ฆฝํธ๋ ๋น๋๊ธฐ ์ฒ๋ฆฌ๊ฐ ๊ธฐ๋ณธ์ด๊ธฐ ๋๋ฌธ์ ์ด๋ฌํ ๋น๋๊ธฐ ํจ์๋ฅผ ๋๊ธฐ ํจ์๋ก
์ฒ๋ฆฌํ ์ ์๊ฒ ํด์ฃผ๋ async & await์ ๋ํด ์์๋ด
์๋ค!
async function f() {
return 1;
}
async๋ ํจ์ ์์ ์์นํฉ๋๋ค. ์ด ํจ์๋ ํด๋น ํ๋ผ๋ฏธ์ค๋ฅผ ๋ฐํํฉ๋๋ค.
async function f() {
return 1;
}
f().then(alert); // 1
// await๋ async ํจ์ ์์์๋ง ๋์ํฉ๋๋ค.
let value = await promise;
await๋ async ํจ์ ์์ ์์ผ๋ฉฐ, ๋ค๋ฅธ ํ๋ผ๋ฏธ์ค๊ฐ ์คํ๋ ๋๊น์ง ๊ธฐ๋ค๋ฆฝ๋๋ค. ์ด๋ฌํ ๋ฌธ๋ฒ์ ์ฌ์ฉํ์ฌ ํ๋ํ ์ ์๋ ๊ฒ๋ค์ด ๋ง์ต๋๋ค.
function timer(time) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve(time)
}, time)
})
}
async function number() {
console.log('inner start')
var time = await timer(1000)
console.log('timer:'+time)
time = await timer(1000)
console.log('timer:'+time)
time = await timer(1000)
console.log('timer:'+time)
console.log('inner finish')
}
async function numberpuls() {
console.log('outside start')
await number()
console.log('outside finish')
}
numberpuls()
์ด๋ ๊ฒ ์ฝ๋๋ฅผ ์ง๋ฉด
์ด๋ ๊ฒ ๋์ต๋๋ค.
โจ ์ด๋ฐ ์์ผ๋ก await๋ฅผ ์ฌ์ฉํ์ฌ ๊ธฐ๋ค๋ฆด ๊ณณ์ ๊ธฐ๋ค๋ฆฌ๊ฒ ํ๊ณ ์งํํ๊ฒ ํ ๊ณณ์ ์งํํ๋๋ก ๊ตฌํํด์ค ์ ์์ต๋๋ค!
(async () => {
let response = await fetch('/article/promise-chaining/user.json')
let user = await response.json()
...
})()
await๋ ๋ง๊ทธ๋๋ก ํ๋ผ๋ฏธ์ค๊ฐ ์ฒ๋ฆฌ๋ ๋๊น์ง ํจ์ ์คํ์ ๊ธฐ๋ค๋ฆฌ๊ฒ ํด์ค๋๋ค. ๊ทธ๋์ ์ฆ์์คํํจ์๋ก ์ฒ์ ๋ ๋๋ง๋ ๋ ๋ฐ๋ก ์ฝ์ด์ค ์๋ ์๊ณ ,
async function showAvatar() {
// JSON ์ฝ๊ธฐ
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
// github ์ฌ์ฉ์ ์ ๋ณด ์ฝ๊ธฐ
let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
let githubUser = await githubResponse.json();
...
}
์ด๋ ๊ฒ await๋ฅผ ๋ถ์ฌ ์์๋๋ก ๋ฐ์ดํฐ๋ฅผ ์ฝ์ด์ฌ ์ ์๊ฒ ๊ตฌํํ ์ ์์ต๋๋ค. ํ๋ผ๋ฏธ์ค๋ฅผ ์ฌ์ฉํ๋ ๊ฒ๋ณด๋ค ๋น๊ต์ ๊ฐ๋จํ๊ณ ๋ณด๊ธฐ ์ฝ๊ฒ ๊ตฌํ๋์์ต๋๋ค.
โ๏ธ ์ฐธ๊ณ ์ฌ์ดํธ
โ๏ธ ์ฐธ๊ณ ์ฌ์ดํธ