-
3. async & awaitJavaScript 2021. 6. 10. 19:36
API to make Promise seem concise, simple and synchronous
clear style of using promise
async is a syntactic sugar that makes Promise easier to use.
1. async
async function fetchUser(){ return new Promise((resolve, reject) => { // do network request in 10 secs... resolve('lexie'); }) } const user = fetchUser(); user.then(console.log);if I put "async" keyword in front of the function, The code block automatically changes to Promise.
2. await ✨
await is only available inside async function
function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function getApple() { await delay(1000); // if happened some error here // throw new Error(`error: apple`); return '🍎'; } async function getBanana(){ await delay(1000); // if happened some error here // throw new Error(`error: banana`); return '🍌'; }Make execute function
function pickFruits1() { return getApple() .then(apple => { return getBanana() .then(banana => `${apple} + ${banana}`); }) } pickFruits1().then(console.log);I can get 🍎 + 🍌 in 2 secs.
It's two returns, but it looks complicated.
So, let's fix this
async function pickFruits2(){ const apple = await getApple(); const banana = await getBanana(); return `${apple} + ${banana}`; } pickFruits2().then(console.log);I can get 🍎 + 🍌 in 2 secs.
And It's more simple.
But I don't need to wait in order to get apple and banana.
I want to get that at the same time.
So,
async function pickFruits3(){ const applePromise = getApple(); const bananaPromise = getBanana(); const apple = await applePromise; const banana = await bananaPromise; return `${apple} + ${banana}`; } pickFruits3().then(console.log);I can get 🍎 + 🍌 in 1 secs.
Because~
As soon as it is created, the function is executed.
In parallel, apples and bananas are obtained at the same time.
But it's not clean code
Finally, I can fix like this through the Promise API
function pickAllFruits(){ return Promise.all([getApple(),getBanana()]) .then(fruits => fruits.join(' + ')); } pickAllFruits().then(console.log);send function as an array type and receives an array of fruits.
I can get 🍎 + 🍌 in 1 secs.
+) Promise.race()
function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function getApple() { await delay(2000); return '🍎'; } async function getBanana(){ await delay(1000); return '🍌'; } function pickOnlyOne(){ return Promise.race([getApple(), getBanana()]); } pickOnlyOne().then(console.log);Among the promises passed to the array, only the first to return the value is passed on.
I can get 🍌 in 1 sec.
There's more detail > https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
'JavaScript' 카테고리의 다른 글
reduce() (0) 2021.06.11 map() (0) 2021.06.10 forEach() (0) 2021.06.10 2. Promise (0) 2021.06.10 1. callback function - Synchronous & Asynchronous (0) 2021.06.10