Node.js Sleep using Async/Await

Are you also downloading lots of data from an API and need a simple way to throttle? Here is a quick snippet on how to use sleep (a function common in many languages).

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function work() {
  console.log('Start sleeping');
  await sleep(5000);
  console.log('Five seconds later');
}

work();

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s