read: JavaScript - Promise
Simple Async Function
Click here to expand...
async function myFirstAsyncFunction() {try {const fulfilledValue = await promise;} catch (rejectedValue) {// …}}If you use the
asynckeyword before a function definition, you can then useawaitwithin the function. When youawaita promise, the function is paused in a non-blocking way until the promise settles. If the promise fulfills, you get the value back. If the promise rejects, the rejected value is thrown.
Promises vs Async/Await
fetch URL and console.log response
Implementation With Promises
function logFetch(url) {return fetch(url).then(response => response.text()).then(text => {console.log(text);}).catch(err => {console.error(‘fetch failed’, err);});}Implementation With Async/Await (easier to read)
async function logFetch(url) {try {const response = await fetch(url);console.log(await response.text());}catch (err) {console.log(‘fetch failed’, err);}}
fetch multiple URLs and console.log responses in order
say we wanted to fetch a series URLs and log them as soon as possible, in the correct order.
Implementation With Promises
function logInOrder(urls) {// fetch all the URLsconst textPromises = urls.map(url => {return fetch(url).then(response => response.text());});// log them in ordertextPromises.reduce((chain, textPromise) => {return chain.then(() => textPromise).then(text => console.log(text));}, Promise.resolve());}Implementation With Async/Await
async function logInOrder(urls) {// fetch all the URLs in parallelconst textPromises = urls.map(async url => {const response = await fetch(url);return response.text();});// log them in sequencefor (const textPromise of textPromises) {console.log(await textPromise);}}
Async Return Values
async functions always returns a promise, whether you use await or not
Click here to expand...
async function hello() {await new Promise(r => setTimeout(r, 2000));return ‘world’;}calling
hello()returns a promise that fulfills with“world”.
async function hello() {await new Promise(r => setTimeout(r, 2000));throw Error(‘bar’);}calling
hello()returns a promise that rejects withError(‘bar’)
Careful! Avoid going too sequential
Click here to expand...
Although you’re writing code that looks synchronous, ensure you don’t miss the opportunity to do things in parallel.
async function series() {await wait(500); // Wait 500ms…await wait(500); // …then wait another 500ms.return “done!”;}The above takes 1000ms to complete, whereas:
async function parallel() {const wait1 = wait(500); // Start a 500ms timer asynchronously…const wait2 = wait(500); // …meaning this timer happens in parallel.await wait1; // Wait 500ms for the first timer…await wait2; // …by which time this timer has already finished.return “done!”;}