DEV Community

Dieunelson Dorcelus
Dieunelson Dorcelus

Posted on

The 3 ways to make an asynchronous method in JavaScript

Today, I decide to write my first post on Dev.to and I choose this subject thanks to my professor named Adrien Joly.
During my studies in the ESGI school, he show us how to make an asynchronous method easily so, I want to share this 3 methods with you !

The setTimeout method

The function named setTimeout() takes a callback in its first parameter and the second is for the timeout in milliseconds.

A callback is a function given in the parameters of another which is responsible for executing it when it needs it.

You can see an example down below :

The promise

A Promise is a JavaScript object which takes 2 callbacks. The first is for the resolving case and the second one is for the rejection.
The asynchronous functions return a Promise to let you define what to do after it executes.

The keyword here is then. When you get a promise, you can call the then() function and give it your resolve function and your rejection method.

You can see an example down below :

Another way to catch the rejection case is to use the catch() function like that :

The async-await

The async keyword is used to specify that a function is asynchronous and the await keyword is used to force the program to wait the function's response before it continue.

Be aware because the function you are waiting can throw an error so surround it with a try-catch block to manage the resolving case and the rejection.

Another thing, if you want to use the await keyword, you have to do it in an asynchronous function.

You can see an example down below :

Personally my favorite is the async-await method but you have to choose the right way depending on the problem you are solving !

Thanks for your time, don't forget to smash the ❀️ button, follow me to stay update and see you in the next post πŸ˜„

Sources

Top comments (2)

Collapse
 
dieunelson profile image
Dieunelson Dorcelus

it's good it's done

Collapse
 
dieunelson profile image
Dieunelson Dorcelus

Thanks for your feedback πŸ™‚
I'll make an update soon πŸ˜πŸ‘