Give an example to demonstrate how can we use async await in Node.js?

See the following example of using async-await pattern:

function wait (timeout) {  

 return new Promise((resolve) => {  

setTimeout(() => {  

  resolve()  

}, timeout);  

 });  

}  

async function requestWithRetry (url) {  

 const MAX_RETRIES = 10;  

 for (let i = 0; i <= MAX_RETRIES; i++) {  

try {  

  return await request(url);  

} catch (err) {  

  const timeout = Math.pow(2, i);  

  console.log('Waiting', timeout, 'ms');  

  await wait(timeout);  

  console.log('Retrying', err.message, i);  

}  

 }  

}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *