The 3 ways to make an asynchronous method in JavaScript
Dieunelson Dorcelus
Posted on March 28, 2021
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
- https://adrienjoly.com/cours-nodejs/
- https://developer.mozilla.org/en-US/docs/Glossary/Callback_function
- https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
Posted on March 28, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.