the sequence of operations in asynchronous programming with async/await

Exploring the concepts of promises, await, and async functions has been a fascinating journey for me. As I delved into the intricacies of promises, I came across an intriguing snippet:

async function async1(){
  console.log('Async 1');
  await async2();  // *
  console.log('After Async 1');
}

async function async2(){
  console.log('FROM async 2');
}


async1();
console.log('Synchronous'); //**

This code snippet produces the following output:

Async 1
FROM async 2
Synchronous
After Async 1

I find myself intrigued by how the execution flows from * to ** in this scenario. It makes me curious about the role of microtasks in this context. How are they being utilized here?

Answer №1

The specific sequence you inquired about, from * to **, does not involve any microtasks being performed immediately. However, a microtask is scheduled for later execution during this sequence.

When an async function is called, it behaves synchronously until encountering the first await, uncaught exception, or return statement. At that point, a promise is returned and the synchronous execution resumes from the caller's context. If there was an exception or a return, a microtask is queued to handle the promise resolution (either rejection or fulfillment).

The parts of the code that are synchronous have been highlighted in yellow:

https://i.sstatic.net/zRDN7.png

In your scenario, when you invoke async1 at the end, its synchronous part runs by logging Async 1, then calls async2 which logs FROM async 2 synchronously. Upon receiving a promise from async2, async1 encounters the await keyword and returns its own promise. Subsequently, synchronous execution proceeds after this call, logging Synchronous.

Between the segments marked with * and **, a microtask is queued to handle the completion of the promise from async2. Once the current task completes, this microtask is executed, resolving async1's promise. Following this, async1 continues its operations, performs the log, and implicitly returns. A final microtask is queued to process this last settlement, but since nothing depends on this promise at that stage, no visible outcome occurs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problem with curved lines in Teechart JavaScript

I am looking to create smoothed lines for my chart. I used teechart.js to make a chart, but it is not working well. Here is an image comparison: the left image is mine and I would like to achieve the smooth line on the right. See example here <!DOCTY ...

In TypeScript, a numerical value can be returned as a string when

After creating a numericQuantity variable that is a casted string quantity, I was puzzled as to why the typeof returns string even though the variable is supposed to be of type :number. let quantity: string = '10'; let numericQuantity: number = q ...

Transferring JavaScript variables to a frame

Struggling to integrate dynamic parameters from the URL into a frame, but nothing seems to be working. I've tried placing them inside and outside the tags, before and after... Anyone have any insights on this? The URL in the top frame is . The initia ...

Optimal Method for Verifying Internet Connectivity in JavaScript

My application, using an instance of Internet Explorer, is constantly checking the internet connection through Ajax. However, due to low bandwidth, Internet Explorer keeps crashing. What are some best practices that can be implemented to prevent this crash ...

Error: The function jQuery(...).hexColorPicker does not exist

I am attempting to utilize a color-picker jQuery plugin. Below is a screenshot of the JavaScript file: https://i.stack.imgur.com/ovRjx.png Here is the code I am using to initialize it: <script type="text/javascript> jQuery(function(){ ...

Determine the instance's name as a string in JavaScript

Currently, I am utilizing Three.js in combination with javascript. Upon running the following line of code: console.log(this.scene.children[1]) I receive the following output in the console within Chrome: https://i.stack.imgur.com/6LBPR.png Is there a w ...

Tips on enhancing the size of FCKEditor's text area?

I am trying to adjust the height of the FCK Text Editor, but encountering some difficulties. Below is the code snippet I am currently using: <tr> <td colspan="2" align="left" valign="middle"> <textarea name="text" id="text" > ...

When subscribed to, the BehaviorSubject will return the object twice

When working with a bank API for payments, the response expected by the banks is that Ban Pay JavaScript will perform an HTTP redirect in the top frame to a completeUrl. The question arises - what should be the completeUrl that I need to provide to the ban ...

Querying specific data from the API using unique identifiers

If the api.football-data.org/v1/competitions holds this data: { "_links": { "teams": { "href": "http://api.football-data.org/v1/competitions/444/teams" } }, "id": 444, "caption": "Campeonato Brasileiro da Série A", ...

Is it possible to utilize the Lit javascript module from a CDN without including the bundled Lit dependencies?

Is there a method to distribute a Lit element created from TypeScript without including the Lit dependencies in the web component bundle? For instance, we can serve the rollup bundle as mentioned here from Unpkg. However, I am curious if it's possibl ...

Request Timeout: The server took too long to respond and the request timed out. Please try again later

I'm encountering an issue when attempting to send a dictionary as a JSON to the express API. The error message I keep receiving is: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={_NSURLErrorFailingURLSessionTaskErrorKe ...

I'm struggling to get this if statement to function properly in my JavaScript code - can anyone help? :)

I have encountered an issue with two functions that are meant to retrieve the user_id of a user. One function obtains the session user_id, while the other retrieves the id from the URL like this: profile.html?id=123. Below is the code snippet: // Extracti ...

Default cross-origin behavior of the Fetch API

According to the Fetch Specifications, the default Fetch mode is 'no-cors'. The specifications state that a request's mode can be "same-origin", "cors", "no-cors", "navigate", or "websocket". Unless otherwise specified, it defaults to "no ...

What is the best way to display a Timepicker within a Dropdown menu using Angular?

While browsing the Bootstrap 4 documentation, I came across a toggleable dropdown feature for the timepicker. However, instead of using vanilla Bootstrap, I wanted to implement this functionality with an Angular module specifically designed for the timepic ...

Exploring the possibilities of utilizing a Kendo grid within an ASP.NET Web API

I am currently using the open source edition of Kendo Web with the Kendo UI Web on ASP.NET MVC 4. My Kendo grid contains the following JavaScript code: <script> $(document).ready(function () { $("#grid").kendoGrid({ dataSource: ...

Can you explain the function of MathUtils.euclideanModulo and how it sets itself apart from the traditional modulo operation?

I'm a little puzzled by the euclideanModulo function in threejs's mathutils. I understand the concept of the modulo operator, but the euclideanModulo function seems to work differently. ( ( n % m ) + m ) % m I tried researching the meaning of "E ...

The html carousel displays stacked images instead of scrolling

I have been staring at this code for what feels like an eternity, trying to figure out why it's only displaying stacked pictures instead of a functioning carousel. Perhaps I overlooked something crucial. Could someone please lend a hand? My code is pr ...

Navigating to an Element in React's Document Object Model

Using React 16.4, I am faced with the need to scroll to a specific DOM element within the application. Since refs are deprecated in React, I am on a quest to find the most elegant solution for this problem. However, I find it challenging to come up with a ...

Shader Material in THREEJS has been replaced with new settings

I am facing an issue with my shader material setup. I have a shader material that is working properly and has a texture attached to it. Now, I want to create two meshes using this shader material but with different textures for each mesh. However, when I ...

The minDate function is malfunctioning when used in conjunction with a date picker that includes a time

I am struggling with the date & time picker not working correctly in the following function. I suspect there is a conflict between the minDate function of the jQuery UI time picker. I have tried changing the script location and removing the minDate funct ...