If you’re an engineer or developer coming from different programming languages, you might have used a native method called sleep()
to stall or pause a method from executing. JavaScript doesn’t have such a native method.
In this article, we will talk about two different ways we can use JavaScript to simulate a sleep function: Promises and async/await functions.
Introduction to Asynchronous Functions
We shouldn’t talk about Promises or async/await functions in JavaScript without first mentioning the setTimeout()
method briefly. This method will show why Promises are needed in JavaScript.
JavaScript is Single-Threaded
When we say JavaScript is a single-threaded language, what we mean is JavaScript only has one call stack and one memory heap. At a high level, this means JavaScript reads code, one line at a time, in order, and must execute a piece of code before moving to the next line. This makes JavaScript synchronous by nature. At times, we need a work around, to make our code asynchronous.
Synchronous Code vs Asynchronous Code
Take a look at this example.
//synchronous console.log("This will print first") console.log("This will print second") console.log("This will print third");
Pretty straightforward, right? Each of the console.logs will print in succession because JavaScript executes them in succession.
Let’s say we want line two to print before line three? How can we essentially print that console.log
out of turn? We can do that with setTimeout()
:
//setTimeout console.log("This will print first") setTimeout(() => { console.log("This will print third") }, 1000); console.log("This will print second");
setTimeout()
allows us to execute a JavaScript function without blocking the thread so other code can run. The first argument is the callback function that runs after a set amount of time (the second argument). The second argument is represented in a number of milliseconds.
This setTimeout()
method mimics the sleep method that’s native in other languages by:
- Setting a timer in the background when the JavaScript engine executes the
setTimeout()
function - Continuing to run other code as the timer does its countdown
- Executing the callback function in
setTimeout()
when the timer reaches zero.
Understanding how setTimeout()
works is crucial to being able to understand how Promises and async/await Functions work. We’ll cover Promises next.
Promises
Creating a Promise
Promises are a way to perform asynchronous logic. The Promise constructor takes in a callback function that has two parameters: resolve and reject. This callback function contains logic that, once finished, will invoke a resolve or reject function with a response passed in.
console.log("before promise") let promise = new Promise((resolve, reject) => { let resolvedFlag = false; //this is just a flag so we can intentionally throw the response to test logic console.log("first"); console.log("second") console.log("third") console.log("fourth"); resolvedFlag = true; //flip resolved to true once all console logs are done if(resolvedFlag) { //if resolved is true invoke the resolve function resolve("Promise resolved"); console.log("after promise"); } else { // else invoke the reject function with a new Error object with message reject(new Error("Promise failed")); console.log("after promise"); } });
The code snippet here demonstrates a simple promise. Promises can be in three states:
pending – Neither resolved or rejected – this is the initial state of the promise
resolved – Successful execution
rejected – Error in execution
Try toggling the resolvedFlag from true to false in the code snippet above to demonstrate the resolution of a resolved promise and a rejected promise.
The main thing to remember is this Promise contains a function that pauses execution of the script until the Promise is resolved or rejected. Then the script resumes.
Using a Promise Response
When we initiate an instance of a Promise, we use then()
and catch()
to lay out the logic we want to use after we have received a response from the returned Promise. This is laid out as one statement – a high level overview looks like:
promise.then(func).catch(func);
In the parentheses that invokes the then and catch methods is an anonymous function that has the response passed in as a parameter.
promise // the promise we created above in prev code snippet. .then(response => { // hits here if successful response // the logic that happens on successful response console.log(response); console.log("after promise"); }) .catch(error => { // catches any errors here. // the logic that happens on error response console.log(error.message); console.log("after promise"); })
Promises are often used when making a call to a database or when making an HTTP request.
Async/Await Functions
The final way we can simulate the sleep()
method is by using async/await functions. Essentially, these asynchronous functions are just another way of constructing the same logic that we would use in Promises, but with less code.
The term async
is placed before the function
keyword in pre-ES6 functions, and before the parameters in ES6+ functions. Any logic you want done before moving on goes in this block of code.
const firstFunction = () => { // logic that you want to have done asynchronously let resolved = true; if(resolved) { let respObj = { message: "Resolved!"}; return respObj.message; } else { let errObj = { message: "Error!"}; return errObj.message; } } const asyncExample = async () => { // async keyword before where parameters would go console.log("Calling function..."); let result = await firstFunction(); // await goes before the invocation of the function that contains your logic. // won't go to the next line until the function is done. console.log(result); return result; } asyncExample() // invokes the async/await function
Using async/await functions result in virtually the same asynchronous promise-based process but with less code.
Conclusion
In this article we took a look at ways to mimic the sleep()
function that is native to other programming languages. We used setTimeout()
to demonstrate the concept of asynchronous JavaScript functions so that we could look at Promises and async/await functions.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.