DEV Community

Dieunelson Dorcelus
Dieunelson Dorcelus

Posted on

2

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 callback method
function theCallback() {
console.log("Hello from the callback !");
}
// The callback will execute in 1000 ms
setTimeout(theCallback,1000);
console.log("Hello World !");

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 :

// The method wich return a promise
function thePromiseGiver() {
return new Promise((resolve, reject) => {
let dice = Math.floor(Math.random() * Math.floor(6));
if (dice>=3) {
resolve(dice);
}else{
reject(new Error(dice));
}
});
}
// What to do if everythings right
function yes () {
console.log("Yes, I'll do it !");
}
// What to do if we have a bad thing
function no () {
console.error("Nope, drop it !");
}
// Execute the first method and THEN call the next one according to the result
thePromiseGiver().then(yes,no);

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

// Execute the first method and THEN call the resolve method or CATCH the rejection
thePromiseGiver().then(yes).catch(no);

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 :

// An asynchronous function
async function theAsynchronousMethod() {
return Math.floor(Math.random() * Math.floor(6));
}
// Another asynchronous function
async function anotherAsynchronousMethod() {
// Wait the response
let dice = await theAsynchronousMethod();
// And continue
if (dice>=3) {
console.log("Yes, I'll do it !");
}else{
throw new Error("Nope, drop it !");
}
}
try{
anotherAsynchronousMethod();
} catch (e) {
console.error(e.message);
}

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

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

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 πŸ˜πŸ‘

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay