js
// async, await (์ ์ฐจ์ )
// .then์ด ํ์ ์์(์ฝ๋๊ฐ ์ง์ ๋ถํด์ง๋ ๊ฒ์ ๋ฐฉ์ง)
// promise then ์ฌ์ฉ
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/*
console.log("ใ
ใ
");
sleep(1000).then(() => console.log("ใ
ใ
ใ
ใ
"));
*/
// async, await ์ฌ์ฉ
async function process() { // ํจ์ ์ ์ ๋งจ ์์ async ์ถ๊ฐ
console.log("ใ
ใ
");
await sleep(1000); // ์ ์๋ ํจ์ ๋ด๋ถ์ promise ์์ await ์ถ๊ฐ
console.log("ํ์ด");
return true; // ๊ฒฐ๊ณผ๊ฐ์ผ๋ก true
}
process() // ์๊ฐ์ฐจ ์์ด ๊ทธ๋ฅ ์๋ํจ
.then(console.log)
/*
// ๊ธฐ๋ณธ ์ํ
// promise๋ฅผ ์ฌ์ฉํ์ ๋์ ๋๊ฐ์ด ์ถ๋ ฅ๋จ
console.log("ใ
ใ
");
setTimeout(() => {
console.log("ใ
ใ
ใ
ใ
");
}, 1000);
*/
js
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function makeError() {
const error = new Error();
throw error;
}
async function process() {
try {
await makeError()
}
catch (aa) {
console.error(aa)
}
finally {
}
}
process();
js
// async ๋ถ์ด๋ฉด ๋น๋๊ธฐ, ํ๋ก๋ฏธ์ค๊ฐ ํธ์ถ๋จ / ๋ด๋ถ๋ฅผ ๋๊ธฐ์ ์ธ ์ฝ๋๋ก ์์ฑ ๊ฐ๋ฅํ๊ฒ
// then์ด ์ค๋ณต์ผ๋ก ๋ฐฐ์น๋๊ณ ๋ ๋ณต์กํด์ง -> ๊น๋ํ๊ฒ ๋ณ๊ฒฝ
// ๋น๋๊ธฐ์ ์ธ ์ฝ๋๊ฐ ๋๊ธฐ์ (์ ์ฐจ์ )์ผ๋ก ๋ณด์ด๋๋ก
function getBanana() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("๐");
}, 3000);
});
}
function getApple() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("๐");
}, 2000);
});
}
// ๋ฐ๋๋์ ์ฌ๊ณผ๋ฅผ ํจ๊ป ๊ฐ์ง๊ณ ์์ ๋ฐฐ์ด๋ก ๋ง๋ฆ
async function fruits() {
const banana = await getBanana(); // promise ์์ await ๋ถ์ฌ์ผ ํจ
const apple = await getApple();
// console.log([banana, apple]);
return [banana, apple];
}
fruits().then((aa) => console.log(aa)); // 4์ด ํ ์ถ๋ ฅ
js
function fetchEgg(chicken) {
// return new Promise((resolve, reject) => {});
return Promise.resolve(`${chicken} -> ๐ฅ`);
}
function friedEgg(egg) {
return Promise.resolve(`${egg} -> ๐ณ`);
}
function getChicken() {
// return Promise.resolve(`๐ฟ -> ๐`);
return Promise.reject(new Error("์นํจ์ ๊ฐ์ง๊ณ ์ฌ ์ ์์"));
}
/*
function makeFriedEgg() {
return getChicken() // ๐ฟ -> ๐
// ๋์ฒด๊ฐ์ ๋ฃ์ด์ค์ ์๋ฌ๊ฐ ๋๋ ์ ์์ ์ผ๋ก ์๋ํ๋๋ก ํจ.
.catch((error) => {
console.log(error.name);
return "๐";
})
.then((chicken) => {
return fetchEgg(chicken);
}) // ๐ฟ -> ๐ -> ๐ฅ
.then((egg) => friedEgg(egg)) // ๐ฟ -> ๐ -> ๐ฅ -> ๐ณ
.then(console.log);
// .catch((error)=>console.log(error.name))
}
*/
// ์๋์ผ๋ก ๋น๋๊ธฐ ํจ์๋ก ๋ณํ
async function makeFriedEgg() {
let chicken;
try {
chicken = await getChicken(); // ๐ฟ -> ๐
} catch (error) {
console.log(error.name);
chicken = "๐";
}
const egg = await fetchEgg(chicken);
const data = await friedEgg(egg);
return console.log(data);
// .catch((error)=>console.log(error.name))
}
makeFriedEgg();