
The value returned by the promise is considered as a return value from the await() expression. Under the async function, we have used the keyword await() to suspend the second console.log() function until the promise has been resolved this takes an average of 4 seconds. We will name this function sleep() however, that does not stop you from naming it to any other name that you may find appropriate. However, using an asynchronous promise-based function, we can use the keyword await() to pause the execution of a piece of code until that promise is fulfilled first. Unlike other programming languages such as C that provide a sleep function, which allows us to sleep a given thread while waiting for another to execute, JavaScript doesn’t have this function.

Use the await() Keyword to Pause Execution of Codes in Node.js Here is a simple example of using the setTimeout() function to execute functions at a different time interval specified as milliseconds.įunction repeatedly executed after every 2 seconds! This function returns an integer known as the timeout ID that can reference the object created by the setTimeout() function.


This method is sort of similar to a while (!condition) sleep loop, but

When working with async functions or observables provided by 3rd party libraries, for example Cloud firestore, I've found functions the waitFor method shown below (TypeScript, but you get the idea.) to be helpful when you need to wait on some process to complete, but you don't want to have to embed callbacks within callbacks within callbacks nor risk an infinite loop.
