What is the functionality of async/await when implemented outside of an async function?

I have a promise declared in a const

const goToWork = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Go to Work'));
});

when attempting to call goToWork(), I encountered the error expression is not callable

To address this issue, I attempted to execute it within an async function:

async function callPromise() {
  return await goToWork;
}

by then using await callPromise(), it returned pending<Promise>. This led me to encapsulate it within another async function:

async function executePromise() {
  console.log(await callPromise());
}

Subsequently, I invoked the function using executePromise() // output: Go To Work

I am curious as to why there was no requirement for executePromise() to run within an async function or be "awaited"

Answer №1

I attempted to run it within an async function:

There is truly no purpose to this function:

async function callPromise() {
  return await goToWork;
}

It serves no real function, as it is essentially the same as:

function callPromise() {
   return goToWork;
}

This function is useless and doesn't serve any meaningful purpose. It indicates a basic misunderstanding of how async/await works.

First of all, all async functions return a promise - always. Therefore, using return await fn() is unnecessary. You might as well use return fn(), as both will return a promise with the same state.

I then tried awaiting callPromise like this: await callPromise() returned pending which led me to store it in another async function like so:

As mentioned before, all async functions return a promise.

I proceeded to execute it with executePromise() // output: Go To Work

There should be no surprise here.

console.log(await callPromise());

This code will display the result of await callPromise(), which will give you the resolved value of the promise that callPromise() returns (if it doesn't reject).

My question is why didn't executePromise() throw an error for not being contained within an async function? Why wasn't it necessary to be "awaited"?

Here's your executePromise function:

async function executePromise() {
  console.log(await callPromise());
}

There is no issue with this function because the await is inside an async function, following the rules of async/await.

When called like this:

executePromise()

It simply runs the function and since it is an async function, it will always return a promise. There is no requirement that calling an async function necessitates using await or must be executed from within another async function.

You can also call it like this:

executePromise().then(...).catch(...)

Or place it within an async function:

async someFunction() {
    try {
        await executePromise();
    } catch(e) {
        // handle error
        console.log(e);
    }
}

Alternatively, you can call it without considering the returned promise:

executePromise();

Calling it without handling the promise means disregarding whether it resolves or rejects and ignoring any resolved value. This may lead to an unresolved rejection if there is no reject handler, but it is permitted if you know the promise will never reject and you are indifferent to when it resolves or what the resolved value is.

Answer №2

Why didn't executePromise() raise an issue about not being in an async function?

However, it actually ran within an async function: async function executePromise().

It's important to note that await is just a shortcut and can be converted back to Promise.then(). For example:

const x = await Promise.resolve('foo')
console.log(x)

works similarly to

Promise.resolve('foo').then(x => console.log(x))

This simplifies understanding the code flow:

async function callPromise() {
  return await goToWork;
}

is comparable to

async function callPromise() {
  return goToWork.then(x => x);
}

And

console.log(await callPromise());

can be seen as

goToWork.then(x => x).then(x => console.log(x))

None of this requires awaiting, but using await enhances readability.

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

End your Idp session and log out using passport-saml

Encountering a 400 bad request error when attempting to log out a user from the idp session. Despite successfully logging out the user from the application/passport session, they remain logged in to the idp session. The logout and callback endpoints are c ...

incorporating a timer into a JavaScript game

I am currently working on a memory card game where I want to include a stopwatch feature. I'm looking to display the time elapsed from when the user selects the first card until they win. However, I am struggling with keeping the stopwatch running smo ...

Updating the list state does not trigger a re-render in Next.js/React

Currently, I have the following state setup: const [places, setPlaces] = useState(false) const [selectedPlaces, setSelectedPlaces] = useState([]) I am asynchronously fetching data to populate the places state by calling an API. The returned array of objec ...

Incorporating modules through System.JS

I integrated angular2-google-maps into my Angular 2 application for utilizing Google Maps functionality. Here is a snippet from my package.json: { "name": "angular2-quickstart", "version": "1.0.0", "scripts": { "start": "tsc && concurre ...

Storing binary data uploaded via AJAX in PHP on the server is essential for maintaining

I successfully imported a .png image file as an Array Buffer. var readSingleFile = function(e) { var file = e.target.files[0]; if (!file) { return; } var reader = new FileReader(); ...

Passing parameters as an array in Angular can be done by using the format: ?category[]=1&category[]=2&category[]=3,

Struggling to send an array using the $http.get() method in AngularJS. Here's my current approach: $http.get('/events.json', {params: {category_id: [1,2]}}); While I anticipate the request to be sent as /events.json?category_id[]=1&cat ...

The optimal method for loading CSS and Javascript from an ajax response within a JavaScript function - Ensuring cross-browser compatibility

I am in a situation where I need jQuery to make sense of an ajax response, but due to latency reasons, I cannot load jQuery on page load. My goal is to be able to dynamically load javascipt and css whenever this ajax call is made. After reading numerous a ...

The margin-top property in CSS is not functioning as intended for a specific pixel value when applied to

I'm having trouble with positioning an icon using margin-top: -35px; under #menu. When I click on the icon, the side navigation bar doesn't work properly. However, if I adjust it to -15px, the side navigation bar displays correctly. Can someone h ...

Choosing items by pressing "shift + up arrow"

I have a collection of elements, each representing one line of text. When you click on an element, it changes color. If you then hold down "shift + arrow up," the items above it are also selected. How can this functionality be implemented? My initial app ...

Developing a personalized Magento2 extension with added support for PWA technologies

Greetings, fellow developers! I find myself at a crossroads when it comes to PWA and custom Magento 2 extensions. As a backend developer for Magento, my knowledge of PWA frontend implementation is lacking. Currently, I am in the process of developing an SE ...

Exception in posting strings or JSON with react.js

Whenever a user clicks on the Signup button, the process I follow to create an account is as follows: Firstly, a new User entry is created in the database. createUser = () =>{ var xhr = new XMLHttpRequest(); xhr.open('POST', 'http:// ...

Changing the color of a div element dynamically with JavaScript

Is there a way to improve the code below so that the background color of this div box changes instantly when clicked, without needing to click twice? function updateBackgroundColor(platz_id) { if(document.getElementById(platz_id).style.backgroundCol ...

Receiving an error when Node.JS spawns a Python process: `JSONDecodeError("Expecting value", s, err.value) from None`

I am attempting to launch a Python process (App.py) from a node.js file (index.js). In the script index.js, the python script App.py is spawned and passed an argument params in the form of a JSON object. App.py then extracts the value from the uParams ele ...

Tips on incorporating a color picker in HTML using jQuery

Looking to implement an HTML color picker with the help of JQuery. Wondering if there is a simpler method to do this without relying on external JQuery libraries? Experimented with <input type="color"> but encountered issues that prevented it from ...

The challenge of managing race conditions in NodeJS with socket.io

Currently, I am facing caching issues with socket io where I need to update values quickly (20 simultaneous requests). However, when I make a get request to check the updated values, the response I receive is not accurate. For example, I expect a result of ...

What steps do I need to take to create a sitemap that includes dynamic routes?

Seeking advice on how to direct search engines to index my dynamic routes. One example is /post/:id, with :id representing the post's ID. Any tips on how to include this in a sitemap? ...

value in the text field changing when focused

Is there a JQuery solution for displaying the keyword when text is entered in the value input? Click here to view an image example. ...

Display a pop-up window upon clicking anywhere on the webpage using jQuery and HTML

Is it possible for me to create a pop-up window that opens a specific website when a user clicks anywhere on the page, similar to pop-up companies? Can this be achieved using HTML, JavaScript, and jQuery? Any help would be greatly appreciated. ...

Avoiding divs from crashing into each other

I've developed a game feature that allows users to chat. Each message is displayed as an absolute positioned element in the body with user x position set as the "left" CSS property. These messages are animated to move to the top of the screen. I want ...

AngularJS is throwing a TypeError because it cannot access the '0' property of an undefined value

for ( var i = 0; i < members.length; i++ ) { var value = value[i]; console.log(value); } Feeling really bewildered by how this could be incorrect... 'i' is set to zero, so it's perplexing how the value couldn' ...