How to return the response from an asynchronous call in Javascript?

Front End TechnologyJavascriptObject Oriented Programming

Asynchronous programming is fairly common in javascript network programming. In this approach, we can download, or perform some time-dependent jobs without locking thecurrent execution flow. Which performs asynchronously as compared to our program, which can be done using async functions in javascript. In this article, we will discuss the techniques to return the response from an asynchronous call in javascript.

Before entering into the concept, let us see in which cases it becomes confusing to developers when asynchronous execution calls are taken into action. Let us see the following situation.

Syntax

function aTrivialFunction() {
   ajaxCall(..., function onSuccess(result) {
      // somehow return result from this function
   });
}
Display ('result of aTrivialFunction', aTrivialFunction() );

In this situation, we are using an AJAX call, which represents a much more general pattern, that is synchronously calling and returning the result of an asynchronous function. Transforming an asynchronous call into a synchronous one is not possible in JavaScript. In the later part of this article, we shall discuss how asynchronous calls work and return the responses.

There are a few different types of an asynchronous functions. These are listed below−

  • Callback − An asynchronous function can be a callback function. This can be passed as a parameter to some other function and will be called with the demanded value whenever it is finished. The callback function can be explained by an example, let us consider the ajaxCall function described in the above code, which takes a callback function as its first parameter. This callback function will be called when the ajaxCall is finished with its HTTP request. Our callback function will take the result of the request as its first parameter.

  • Promises − Promises are new in javascript and came with javascript version ECMAScript 6 (ES2015). We can state a promise is an object that is synchronously returned from an asynchronous function and which can track the state of that function. A promise can have the following states−

          Pending: This is the initial phase, which is neither fulfilled nor rejected

          Fulfilled: When the operations have been completed successfully

          Rejected: When the operation has failed due to some erroneous condition

  • Async/Await − The async and await keywords increase the readability of the code and look more synchronous. Long nested promises can be handled by using them.

Returning results from asynchronous function call

To solve the above-mentioned problem, we can return a “promise” object without returning the direct result. By returning the promises the invoker function will deal with the results as soon as it arrives. Let us see the similar syntax for solving the problem.

Syntax

function aTrivialFunction() {
   return new Promise( (resolve, reject) => {
      ajaxCall(..., function onSuccess(result) {
         resolve( result );
      });
   });
}
const result = await aTrivialFunction()
Display ( 'result of aTrivialFunction', result );

In the above syntax, we are returning a promise object. This promise object is an object that is returned immediately and can be used to keep track of the state of our asynchronous call. Whenever the resolve function is being called, it will signal that the asynchronous call has been completed, in other words, the promise has been resolved. Promise also words with error case, but in this example, it is not shown here. To indicate an error, we can just call the reject function instead. We have used await keyword to deal with promises. As we can see, we can simply await the promise that is returned by our function. This almost looks like synchronous code.

We can only use await when we are in the async function. So, in case we are in the global execution context of our program, we need to wrap our code into an asynchronous environment, the syntax can be like below−

Syntax

(async () => {
   const res = await myFunction();
   console.log( 'Getting result from asynchronous environment:', res);
})();

Conclusion

Transforming an asynchronous function into a synchronous one is not possible. However, we do not need to do so. We can use async and await keywords, using them, we can organize our code in a way that reads almost like synchronous code and we do not lose the readability and flexibility that asynchronous codes. If we want a synchronized system asynchronous programming will be a helpful approach to deal with this.

raja
Updated on 23-Aug-2022 07:33:53

Advertisements