Can you explain the distinction between incorporating and excluding the keyword "await" in the following code snippets?

Currently, I'm diving into an MDN article that covers async/await. I've grasped the rationale behind using the async keyword preceding functions, yet there's a bit of uncertainty regarding the await keyword. Although I've researched "await" extensively and comprehend the general idea, examples still leave me puzzled. Take this simple snippet of code (featured in the MDN article) utilizing async/await.

async function hello() {
  return greeting = await Promise.resolve("Hello");
};

hello().then(value => console.log(value));

It's no surprise that this snippet logs "Hello" to the console. However, even if we remove "await," the result remains consistent.

async function hello() {
  return greeting = Promise.resolve("Hello"); // without await
};

hello().then(value => console.log(value));

Could someone shed light on what exactly the await keyword followed by Promise.resolve accomplishes? Why does the output stay unchanged when it's not included? Appreciate any insights.

Answer №1

Modern JavaScript engines have made it so that there is no distinction between using return await somePromise and just return somePromise at the top level of a function. However, if this code were within a control block like a try/catch, the difference would be noticeable.

This particular change occurred somewhat recently. Prior to ES2020, using return await would add an additional async "tick" into the process. This was optimized out as part of a normative change in ES2020 specifically for native promises being awaited (there may still be a slight difference with non-native thenables).

To clarify, consider the following two examples:

async function example() {
    try {
        return await somethingReturningAPromise();
    } catch (e) {
        // handle error/rejection
    }
}

versus

async function example() {
    try {
        return somethingReturningAPromise();
    } catch (e) {
        // handle error/rejection
    }
}

In the first example, any rejection from somethingReturningAPromise() will be caught in the catch block due to the await. In the second example, the promise is simply returned without going through the catch.

When not within a control structure, the use of await is mainly a stylistic choice.

Answer №2

It's important to remember that async/await is essentially a more user-friendly interface for handling promises.

An async function always returns a promise automatically (as soon as the first await or return statement is encountered) which will be resolved once the function finishes executing. The value of the resolved promise will match the returned value of the function.

async enables you to utilize await within the asynchronous scope, where await only makes sense when preceding a promise (such as another async function call or a promise created on-the-fly with new Promise()). Using await before non-promise values won't cause any issues.

await signifies a pause in execution and instructs the engine to wait until the promise is fulfilled before continuing. The resulting value of the fulfilled promise will then be given back or 'returned' by await.

For practical illustration:

In your original code snippet:

async function hello() {
  const greeting = await Promise.resolve("Hello"); // HERE I CAN USE await BECAUSE I'M INSIDE AN async SCOPE.
  console.log('I will be printed after above promise is resolved.');
  return greeting;
};

hello().then(value => console.log(value));

In a streamlined version of your code, the async keyword could be omitted entirely:

function hello() {
  return Promise.resolve("Hello");
};

hello().then(value => console.log(value));

If you have any uncertainties, feel free to reach out.

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

Encountering a peculiar problem with the Bootstrap Carousel where the first slide fails to load

There seems to be an issue with the bootstrap carousel where the first slide appears empty initially, but once you slide to the second slide it starts working fine. Navigating through all slides is still possible. <div id="mediakit_carousel" class="car ...

Following the implementation of the YITH ajax navigation filter, my jQuery scripts are no longer functioning as

I'm having trouble with using yith ajax navigation in my theme. Everything works perfectly until I click on an element to filter, at which point my jquery codes stop working. The team at yith suggests: If your product list contains JavaScript cod ...

How can the onclick attribute be modified in an HTML document?

I am looking to update the data-pro-bar-percent attribute of a progress bar from 80 to 100 when a specific link is clicked. The change in attribute needs to be as follows: data-pro-bar-percent="80" --> data-pro-bar-percent="100" This is the current HTML ...

Displaying a div in Vue.js when a button is clicked and an array is filled with

Hey there! I'm having an issue with displaying weather information for a specific location. I want to show the weather details in a div only when a button is clicked. Despite successfully fetching data from the API, I'm struggling to hide the wea ...

There are various IDs in the output and I only require one specific ID

I have a JSON fetcher that is functioning properly. However, whenever I request an ID, it returns all the IDs present in the JSON data. Is there a way to retrieve only the latest ID? This is my first time working with JSON so I am still learning. $(docu ...

I am currently struggling with the mapquest GeoJson integration within my Node/Express application. I keep encountering an error message that reads "body used already."

I attempted to utilize the mapquest API by following the provided documentation, however I encountered an error message: HttpError: body used already for: Below is my geoCoder.js configuration: const NodeGeocoder = require('node-geocoder'); con ...

issue with visibility of checkbox in material ui table row

In a separate file called TradesTable.js, I have created a table using Material UI for my React app. const DummyTableRow = (props) => { let myRows = props.trades.map((trade, index) => { return <TableRow> <TableRowColumn ...

Fetch information that was transmitted through an ajax post submission

How can I retrieve JSON formatted data sent using an ajax post request if the keys and number of objects are unknown when using $_POST["name"];? I am currently working on a website that functions as a simple online store where customers can choose items m ...

Send a request to templateUrl

After experimenting with AngularJS, I decided to create a dynamic route system that funnels all routes through a single PHP file. This was motivated by my desire to prevent users from accessing raw templateUrl files and seeing unstyled partial pages. Prio ...

Upgrading an Express 2.x application to Express 3.0

I am currently studying NodeJs and Express and am in the process of converting a tutorial app from Express 2.5.9 to version 3.0. The following code is now causing an error "500 Error: Failed to lookup view "views/login". How can I update this to render cor ...

Creating a JSON data array for Highcharts visualization: rearranging values for xAxis and columns

I am facing an issue with my column chart where JSON data is being parsed in the "normal" form: Years are displayed on the xAxis and values on the yAxis (check out the fiddle here): array( array( "name" => "Bangladesh", ...

What could be causing the <td> onclick event to fail in asp.net?

Having an issue with making a <td> clickable to display a div. Check out my code snippet below: <td id="tdmord" style="padding-left: 15px; color: #86A7C5; padding-right: 15px; font-family: Arial; font-size: small;" onclick="return showDiv1()"& ...

Sketch a straight path starting from the coordinates x,y at a specified angle and length

Is there a way to draw a line in Javascript starting from a specific x/y position with a given length and angle, without having to define two separate points? I have the x/y origin, angle, and length available. The line should be placed on top of a regula ...

Chokidar operates smoothly from the command line, but fails to function properly when invoked through the use of 'npm run'

I've implemented a script that monitors Tailwind CSS files using Chokidar. The script works perfectly when I execute the command in the CLI using chokidar 'tailwind.config.js' --initial=true -c 'npm run build-tailwind'. It successf ...

What are some ways to enhance the functionality of the initComplete feature in Dat

$('#example').dataTable( { "initComplete": function(settings, json) { alert( 'DataTables has finished its initialisation.' ); } } ); Is there a way to extend the initComplete function for other languages? $.extend( true, $.f ...

I am having difficulty aligning the vertical touch event owl carousel

Here is the link: "jsfiddle.net/nLJ79/". Can you try to find a solution to make the owl carousel vertical? ...

managing the focus and blur events within an Angular 1.5 component

While working on an angular js project recently, I encountered a situation involving handling focus and blur events in a textbox. My specific scenario required adding the $ sign when focus is lost from the textbox and removing it when the textbox is focuse ...

Tips on effectively utilizing dynamic data with Google Charts

I am working on creating a dynamic chart using Google Charts with multiple CSV files. I want to display a different chart depending on the selection made by the user. The first file loads successfully and displays a chart, but the $("#selection").change(.. ...

Stop the execution of javascript code based on the screen width

On my website, I have two menus located in different sections of the page. One menu is shown when the screen width is greater than 555px, while the other menu appears when the screen width is less than or equal to 555px. Although the menus are essentially ...

What is the best way to determine the width and height of text within a TextArea using JavaScript in an HTML document

Imagine this scenario: https://i.stack.imgur.com/cliKE.png I am looking to determine the size of the red box within the textarea. Specifically, I want to measure the dimensions of the text itself, not the dimensions of the entire textarea. The HTML code ...