[TIL 2021.10.14] js async await (완강)
Today I Learned
async, await
// 1. async 개선전
function fetchUser() {
// doing network request taking 10 secs..
// return 'kyu';
// instead of those code above
return new Promise((resolve, reject) => {
// doing network request taking 10 secs..
resolve('kyu');
})
}
const user = fetchUser(); // it'll take 10 secs
user.then(console.log);
console.log(user); // and return this
// the problem is nothing will appear on screen while doing that
// -----------------------위에 기존 Promise를 async로 개선-----------------------///
// 1. async 개선후
async function fetchUser() {
// doing network request taking 10 secs..
return 'kyu';
}
const user2 = fetchUser(); // it'll take 10 secs
user2.then(console.log);
// easy money
// -------------------------------------------------------------------------
// 2. await
// await은 async가 붙은 함수에만 사용가능
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function getApple() {
await delay(2000);
return 'apple';
}
async function getBanana() {
await delay(1000);
return 'banana';
}
// function pickFruits() {
// return getApple().then(apple => {
// return getBanana().then(banana => `${apple} + ${banana}`);
// });
// }
// async function pickFruits() {
// const apple = await getApple();
// const banana = await getBanana();
// return `${apple} + ${banana}`;
// }
// pickFruits().then(console.log);
// 3. useful Promise APIs
function pickAllFruits() {
return Promise.all([getApple(), getBanana()])
.then(fruits => fruits.join(' + '));
}
pickAllFruits().then(console.log);
function pickOnlyOne() {
return Promise.race([getApple(), getBanana()]);
}
pickOnlyOne().then(console.log);
done youtube js tutorial by dream coding with ellie 1~13
Author And Source
이 문제에 관하여([TIL 2021.10.14] js async await (완강)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@kyukim/20211014저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)