How to change synchronous code to asynchronous code#
Remember the piece of code we wrote when we were talking about how synchronous code can create problems if we want to run different pieces of code at the same time? The one with the user login function? Since we know how to use promises in JavaScript now, let’s see how to make the code look and run better. For a quick refresher, our old synchronous code looked like this:
To refactor this piece of code and make it asynchronous, we will add a new promise like so:
Here, we added a new promise object and put the setTimeout
function inside of it. Our code looks cleaner now,will run smoothly, and will show what we want after just two seconds. As usual, if we get the data we requested, we will pass resolve
next to ‘{usermail: email}
in place of return
, and we’re good to go. We can also call reject
and chain a catch method that will tell us our data request has been rejected.
How then do we successfully call our userLogin
function and pass new parameters? Before we look at that, we have to note that in practice, you may not even have to write the preceding code from above. Most times, when you request data from a web API, it automatically returns a promise. We have just written it all out to see how it works under the hood.
If you remember, when we tried to test our function and console log the newUser
variable, we got undefined
. To call our function now with new parameters, we will add a then
method like so:
Here, we are executing the userLogin
function with a new email and password. We have also attached a then
method that gives us access to this new user. This piece of code will return this new user’s data, just like we asked it. Compared to what our code looked like before, this is easier to read, cleaner, and more effective. Knowing how to write asynchronous code is important as a developer. It helps you run different pieces of code separately from your main application.