Invoking a function containing an await statement does not pause the execution flow until the corresponding promise is fulfilled

Imagine a situation like this:

function process1(): Promise<string> {
  return new Promise((resolve, reject) => {
    // do something
    const response = true;
    setTimeout(() => {
      if (response) {
        resolve("success");
      } else {
        reject("error");
      }
    }, 5000);
  });
}

async function process2(): Promise<string> {
  const result = await method1();
  // perform additional processing and return a different output
  const result2 = result + "1";
  return result2;
}

function process3(): void {
  console.log("test 1");
  const result = process2();
  console.log("test 2");
}

process3();

I find it puzzling why process2() doesn't wait for the result despite having an await. Adding await to the call of process2() in process3() makes it work:

async function process3(): Promise<string> {
  console.log("test 1");
  const result = await process2();
  console.log("test 2");
}

The concept of how async/await operates is still unclear to me even after going through numerous blog posts, Mozilla documentation, and stackoverflow answers.

One of the comments mentioned that "you can't escape asynchrony". It was further explained that since any async function would return a promise, all calls must be awaited throughout the function chain.

I hope someone can shed some light on this for me. Thank you.

Answer №1

https://www.w3schools.com/js/js_async.asp

Each async function in JavaScript will ultimately result in a promise that travels up the chain to the initial call.

There exist certain libraries designed to enable synchronous calls from promises if needed.

Ultimately, it's important to understand that this behavior is inherent to the nature of JavaScript.

Answer №2

  • Identify asynchronous functions by marking them with the async keyword
  • If a function awaits an asynchronous function, it must also be declared as async to maintain proper flow of execution
  • Always use the await keyword when calling asynchronous functions, especially if you need the result to proceed with the code; only exception is for top-level where then syntax can be used instead

async function process1() {
  return new Promise((resolve, reject) => { 
    setTimeout(() => resolve(1), 5000);
  });
}

async function process2() {
  console.log("Initiating process 2");
  const outcome = await process1();
  console.log("Process 2 completed");
  return outcome + 1
}

async function process3() {
  console.log("Begin process 3");
  const outcome = await process2();
  console.log("Process 3 wrapped up");
  return outcome + 1
}

process3().then(result => console.log(result))

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

Delete the parent div when the button is clicked

trying to create a dynamic button system to add/remove inputs on clicks. I have the addButton working but not the deleteButton. What am I missing? $(document).ready(function() { var maxFields = 20; var addButton = $('#plusOne'); va ...

Invoking a function in a React component from another component

I am trying to implement a page with the structure shown below: const Upload = (props) => { return ( <BaseLayout> <ToolbarSelection /> <Box> <FileDropArea /> </ ...

The functionality of Jquery UI is not compatible with version 1.12

Incorporating jQuery UI into my current project has presented some challenges. Both the jquery-ui.min.css and jquery-ui.min.js files are version 1.12, so I opted for the latest jQuery version, jquery-3.2.1.min.js. Specifically, I decided to test the datep ...

Tips for Ensuring a JavaScript Contact Form Submits Successfully

Snippet of HTML Code for Contact Form: Contact Me <label for="Name">Name:</label> <input type="text" name="name" id="Name" accesskey="N" tabindex="1"> ...

"Learn the trick of converting a stream into an array seamlessly with RxJs.toArray function without the need to finish the

In order to allow users to filter data by passing IDs, I have created a subject that can send an array of GUIDs: selectedVacancies: Subject<string[]> = new Subject(); selectedVacancies.next(['a00652cd-c11e-465f-ac09-aa4d3ab056c9', ...

There is no matching signature for Type when using withStyles

Struggling to convert my React App to typescript, I keep encountering the error below and cannot decipher its meaning. The app functions perfectly in plain JS. My package version is material-ui@next TS2345: Argument of type 'typeof ApplicationMenu&a ...

Unable to encode value that is not an enumerated type

Working with my graphQL API using typescript and type-graphql, I am attempting to perform a mutation that has an inputType with an enum value defined as shown below export enum GenderType { female = 'female', male = 'male', } regis ...

The state returned by React Redux does not meet the expected results

I recently implemented a like function on the backend using Node and MongoDB. This function successfully returns the post with an updated likes counter, which I tested using Postman. The post object contains properties such as likes, _id, by, createdAt, an ...

Formatting Dates in Node.js

Can someone assist me in understanding how to properly format the print date shown below? Thu Sep 06 2018 18:18:26 GMT+0530 I attempted to use console.log(new Date()) However, the output generated was 2018-09-06T12:48:25.776Z I am unsure of how to co ...

The error message "TypeScript reflect-metadata Cannot find name 'Symbol'" indicates that TypeScript is unable to locate

While browsing through http://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators, I encountered an issue where it could not find the Symbol. I was unsure whether this is related to the usage of reflect-metadata or if it was previously in ...

jQuery live function is not functioning as anticipated

I am facing issues with ajax requests and simple <input type="submit"/>. I have a practice of loading views within other views, in a modular way, using jQuery's .load(url) function to move from one view to another. The problem arises when I loa ...

Choosing a subset of data within a JavaScript object with the help of jQuery/jHashtable

Here is an object that I am working with: var data = { "info" : [{ "title": "Desemberkonsert", "description": "MangerFHS 09/10" }], "playlist" : [ { "title": "In This Place", "description": "Excalibur", "href": "desemberkonsert_in-this-place", "url": "flv ...

Optimal method for managing errors in Flask when handling AJAX requests from the front end

I'm currently working on a React application that communicates with a Python Flask server. One of the features I am adding allows users to change their passwords. To do this, an AJAX request is sent from React to Flask, containing both the old and ne ...

The toggle checkbox feature in AngularJS seems to be malfunctioning as it is constantly stuck in the "off"

I am trying to display the on and off status based on a scope variable. However, it always shows as off, even when it should be on or checked. In the console window, it shows as checked, but on the toggle button it displays as off Here is the HTML code: ...

Changing the shape of a background using CSS when hovering

My Bootstrap navigation has a unique setup, as shown below. I've observed that many users tend to only interact with the headings and ignore the submenus where the actual products are located. To address this issue, I want to change the design of th ...

What causes the discrepancy between the nodejs package on GitHub and the version downloaded through npm?

After committing to installing a nodejs package with npm install -g package_name, I noticed that some of the downloaded packages have different files compared to the same package on Github. Why is this discrepancy present? ...

Steps for creating a sleek vertical slider with transitional effects using JavaScript and HTML

Take a look at my code snippet: <table> <tr> <td onclick="shownav()">Equations of Circle <div id="myDownnav" class="sidenav"> <a>General Info</a> <a>In Pola ...

Incorporate personalized buttons into the header navigation for each view using VueJS

In my VueJS project, I attempted to include custom buttons in the sub navigation menu which could be customized for each view. Initially, I tried adding a simple property to the main data element, but that didn't yield the desired results. Then, I cam ...

pagination functionality incorporated into element ui tables

Issue with Element UI: when a checkbox is selected and the page is changed, the selected rows' checkboxes are removed. I need to retain the selection items while paging so that users can select items from multiple pages without losing the selections f ...

turn on labels for every individual cell in the bar graph

I'm working on setting labels of A, B, and C for each bar chart cell to display all my data on the chart. I attempted using data.addColumn('string', 'Alphabets'); but it's not functioning as expected. It seems like a simple ta ...