DEV Community

3BiEiD
3BiEiD

Posted on

Methods of Handling Asynchronous Code

JavaScript provides three methods of handling asynchronous code: callbacks, promises, and async/await. Let's discuss each.

Callbacks

Asynchronous callbacks are functions that are passed to another function so that the internal function can begin running code in the background. As soon as we need to handle multiple asynchronous operations, Callback Functions nest into one another, which leads to callback hell. This makes callbacks an old-fashioned method of writing asynchronous Javascript.

This is the basic syntax of the callback function:

function demoFunction(callback){
  callback();
}
Enter fullscreen mode Exit fullscreen mode

Promises

Promises are used to track asynchronous operations, whether the asynchronous event has been executed or not. Promises have four states:
Pending: The initial state of promise before the event happens not fulfilled or rejected yet.
Fulfilled: Action/Operation related to the promise completed successfully.
Rejected: Action/Operation related to the promise failed
Settled: Promise has been fulfilled or rejected

let promise = new Promise (function(resolve, reject) {
  ... code
})
Enter fullscreen mode Exit fullscreen mode

Async/Await

Async/await works with promises in asynchronous functions, making asynchronous code appear more like synchronous or procedural code. A promise is returned by an asynchronous function.

The syntax of an async function is as follows:

async function name(parameter1, parameter2, ...paramaterN) {
  // statements
}
Enter fullscreen mode Exit fullscreen mode

Await can only be used in async functions, and it is used for calling async functions. Await blocks the execution of the code inside the async function in which it is contained until the async function has either resolved or been rejected.

Here is the syntax of the await function:

let result = await promise;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)