Promise async await
JS์ ๋น๋๊ธฐ๐
Promise
1. Producer
const promise = new Promise((reslove, reject) => {
resolve('junhyeok') //์ฑ๊ณตํ์๋
reject(new Error('๋ญ๊ฐ ์์๋์ด!')) //์คํจํ์๋
console.log("asd");
});
2. Consumers : then, catch, finally
promise
.then((success) => {
console.log(success); // junhyeok
})
.catch((error) => {
cosole.log(error);
})
.finally(() => {
console.log("๋ง์ง๋ง์ ๊ทธ๋ฅ ์คํ์์ผ๋ด");
});
const Abcd = new Promise((resolve, reject) => {
resolve(1);
});
Abcd.then((success) => {
//2
success * 2;
})
.then((success) => {
//6
success * 3;
})
.then((success) => {
return new Promise((resolve, reject) => {
//5
resolve(success - 1);
}).then((success) => {
console.log(success); //5
});
});
example
class UserStorage {
//
loginUser(id, pw) {
return new Promise((resolve, reject) => {
if (๋ด๊ฐ์ํ๋๊ฒ๋๋ค๋ฉด) {
resolve(id);
} else {
reject(new Error("์คํจ..."));
}
});
}
getRoles(user) {
return new Promise((resolve, reject) => {
if (user === "abc") {
resolve({ name: "abc", role: "์ด์ฝ๋ฆฟ" });
} else {
reject(new Error("์คํจ.."));
}
});
}
}
UserStorage.loginUser(id, pw)
.then((id) => {
UserStorage.getRoles(id);
})
.then((user) => {
console.log(`${user.name} , ${user.role} ์
๋๋ค.`);
})
.catch(console.log);
์์ฝ : loginUser์ id์pw๋ฅผ ๋ฃ๊ณ ์กฐ๊ฑด๋ฌธ์ ์ฑ๋ฆฝํ๋ฉด ๊ทธ๊ฐ์ getRoles์ ๋ฃ์ด์ฃผ๊ณ getRoles์ ์กฐ๊ฑด์ด ์ฑ๋ฆฝํ๋ฉด ์ถ๋ ฅํ๋ค.
async and await
async
function Abcd() {
return new Promise((resolve, reject) => {
resolve("abc");
});
}
//========================================================================
async function Abcd() {
return "abc";
}
await
async function Abcd() {
const a = await delay(3000);
return a;
}
async function Abcd() {
try {
const a = await getA();
const b = await getB();
} catch (error) {
console.log;
}
return `${a} + ${b}`;
}
๋ณ๋ ฌ์ ์ฒ๋ฆฌ
function Abcd() {
return Promise.all([getA(), getB()]).then((๋ฐฐ์ด) => console.log(๋ฐฐ์ด));
}
//==================================================================================
function Abcd() {
return Promise.race([getA(), getB()]);
}
Abcd().then((๋๊ฐ์ค๋น ๋ฅธ๊ฒ) => console.log(๋๊ฐ์ค๋น ๋ฅธ๊ฒ)); // then(console.log)
์์ฝ : async await์ ๋๊ธฐ์ ์ผ๋ก ์ฝ๋๋ฅผ ์์ฑํ ์ ์๊ฒ ํด์ค์ผ๋ก์จ ์ข ๋ ์ง๊ด์ ์ด๋ค. Promise ์ฒด์ด๋์ผ๋ก ์์ฑ์ ํ๋ค๋ฉด ๋ณ์์ ์๋ช ์ฃผ๊ธฐ๊ฐ ๋ช ํํ์ง๋ง ์ด๊ฒ์ ์ธ์ ๋ ์ง ์ฐ์ผ ์ ์๋ค. ๋ฌผ๋ก ์ด๊ฒ์ด ๋จ์ ์ด ๋ ์ ๋ ์๋ค.