Here, the execution of the function m is interrupted after the call to aPr , and resumes when the promise returned by aPr has been resolved. The resolved value is then assigned to resultFromA. We thus obtain a code that executes asynchronous functions with a syntax close to the one used for synchronous calls. Note that the functions aPr, bPr, and cPr, are the same as in the previous example and return promises. Unlike the switch from callbacks to promises, asynchronous functions are not a paradigm shift and can be adopted gradually or partially.
An asynchronous function itself returns a promise, which is resolved when the function’s execution is completed, along with the value eventually returned. Note that the await operator is implicit in the case of return, so “return await p;” is equivalent to “return p;”.
Four examples to understand the benefits of asynchronous functions
One of the main advantages of asynchronous functions is obvious: the code is more concise and cleaner. There is no more chaining of calls to then and function declarations. But there are many other advantages to using asynchronous functions, and I will illustrate four of them here.
Synchronous and asynchronous errors
When using the classic promise syntax, there are two types of errors to handle: errors produced by synchronous calls and promises. With await, promises are used as synchronous calls, including error handling. Let’s take the following code :
Social media