javascript resolve order awaited

Is it safe to assume that the async function will release the execution in the order it was initiated?

For instance, consider this code snippet:

class Bar {
    public barPromise = new Promise(resolve => setTimeout(resolve, 1000));
    public data = null;

    public async setData(d) {
        await this.barPromise;
        this.data = d;
    }
}

async function initialize() {
    const bar = new Bar();
    bar.setData(1);
    bar.setData(2);
    bar.setData(3);
    await bar.barPromise;
    console.log(bar.data);
}

initialize();

Would it be reasonable to expect the output to be 3? It's important to note that the initialize() function doesn't pause during calls to bar.setData(x). Instead, it continues until waiting for the resolution of the promise with await bar.barPromise, resulting in multiple awaits waiting for bar.barPromise to resolve.

This example serves merely as a demonstration. In practical scenarios, I would avoid using such patterns. In my circumstances, I rely on a third-party library that initializes at some point, and I want users of my class to perceive it as synchronous so they can safely invoke methods whenever needed, assured that the outcome will be consistent. Therefore, if a setting is updated twice, only the last value will persist.

Answer №1

Given that there is just one promise being utilized and all functions are dependent on that single promise, it is indeed possible to execute them in the desired sequence. This is due to the fact that the callbacks registered with a promise will run sequentially based on their registration order.

In your particular code scenario:

foo.setValue(1); // => this action happens first, setting the value to 1
foo.setValue(2); // => this follows as second, updating the value to 2
foo.setValue(3); // => the third step sets the value to 3
await foo.fooPromise; // => by waiting for the fooPromise, the console.log operation stalls until the setValue calls complete
console.log(foo.value); // => consistently displays the value as 3

If instead of awaiting the same promise within setValue, you were to create a fresh promise, the predictable outcome of the console.log would not be guaranteed.

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

Tips for resolving this unhandled error in React TypeScript

After creating a program in React TypeScript, I encountered an uncaught error. Despite running and debugging tests and conducting extensive research on Google, I have been unable to resolve this issue on my own. Therefore, I am reaching out for assistance ...

Tips for preventing repetition in http subscribe blocks across various components

Imagine a scenario where there is a service used for making HTTP request calls. There are two different components (which could be more than two) that need to send the same request using the same observables via this service. After receiving the result, it ...

What is the method to group a TypeScript array based on a key from an object within the array?

I am dealing with an array called products that requires grouping based on the Product._shop_id. export class Product { _id: string; _shop_id: string; } export class Variant { variant_id: string; } export interface ShoppingCart { Variant: ...

Developing a Javascript object using Typescript

Trying my hand at crafting a TypeScript object from JavaScript. The specific JavaScript object I'm attempting to construct can be found here: https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.10.2/chess.js In the provided JavaScript example, the obj ...

Utilize knex.js and TypeScript to create queries with specific conditions

I am trying to create a dynamic query that will include a where clause based on whether the variables name and/or city are passed. While I couldn't find a specific method for this in the documentation, I attempted to add the where clauses directly to ...

what is the best way to determine the variable type in typescript and angular?

How can I determine the type of a variable in TypeScript with Angular? import { Component } from '@angular/core'; interface Abc { name : string } @Component({ selector: 'my-app', templateUrl: './app.component.html', ...

Error: Unable to instantiate Razorpay as a constructor

Having some trouble integrating Razorpay with Node TypeScript. The issue appears to be related to the const variable razor. Any help or insights would be greatly appreciated. Thank you! import * as Razorpay from 'razorpay'; const razor = new ...

When a function is included in an object, it transforms into something other than a function

In my model, it looks like this: export default class UserObject { name: string; id: string; validateInsert() { } } If I interact with the model in this way: const modelUser: UserModel = new UserModel(); modelUser.ID = 1; modelUser ...

Incorporating Java project dependencies into an npm project

I'm facing a challenge in my development process, where I need to incorporate dependencies from a Maven Java project into my package.json file within my Vue/Typescript project. These dependencies are crucial for accessing specific data types that my p ...

Tips for creating a Next.js "Link" component with an optional "href" property

I've created a custom React function using typescript for the Next.js Link component. The "href" property is necessary for the "Link" to be used anywhere, so it couldn't be utilized as a button that functions as a submit button in forms. import N ...

How does Typescript handle dependency injection compared to the JSDoc typedef module import for defining types?

Currently, I am facing an issue with defining dependency injection in Typescript. In my experience with JSDoc, I have used typedef import('./classModule.js').default myClass. To illustrate, let's consider multiple classes stored in their o ...

How to pass data/props to a dynamic page in NextJS?

Currently, I am facing a challenge in my NextJS project where I am struggling to pass data into dynamically generated pages. In this application, I fetch data from an Amazon S3 bucket and then map it. The fetching process works flawlessly, generating a se ...

Typescript's struggle with dynamic property typings in React Functional components

When working with a react functional component and passing a prop that can be either a string or an object, I encountered an issue. It functioned fine without typescript, but as soon as typescript was added, it couldn't comprehend the dynamic nature o ...

Tips for displaying only the initial 15 characters of a text value

The content extracted from a .ts file is being displayed on the home.html page. I am aiming to display only the initial 15 characters followed by 3 dots (...). Despite my efforts, the following code snippet is not functioning as expected: home.html < ...

React: The Material-UI autocomplete input, controlled with the React Hook Form `<controller>` component, experiences issues when the `multiple` prop is set to `true`

Currently facing challenges with managing an autocomplete MUI component using the <controller> component in react-hook-form. Take a look at the code snippet below: <Controller control={control} name="rooms" render={({ field }) =&g ...

What is the process of converting an Array that is nested within an Object?

I am facing compile errors while attempting to convert an Object containing an Array of Objects. Here is the initial structure: export interface CourseRaw { metaInfo: MetaInfoRaw; gameCode: number; gameText: string; images?: ImageRaw[]; // Having ...

Converting an array of objects to an array of JSON objects in TypeScript

My dilemma lies in the data I have uploaded under the _attachments variable: https://i.sstatic.net/jnFNH.png My aim is to format this data for insertion in the following structure: "_attachments": [ { "container": "string", "fileName": "string" ...

An issue occurred in NestJs where it was unable to access the property '__guards__' because it was undefined

Currently, I am in the process of incorporating a basic authentication system into my Nest project. After including the following line in my controller: @UseGuards(AuthGuard('local')) I encountered this error message: ERROR [ExceptionHandler] C ...

Error encountered during Vercel build process: TypeError - _.map function is not recognized

I keep running into a typeError when I try to deploy my next.js application on Vercel TypeError: items.map is not a function at SearchResults (/vercel/path0/.next/server/app/exercises/page.js:568:29) at process.processTicksAndRejections (node:internal/proc ...

Expanding the capabilities of indexable types in Typescript

I recently created an interface for form validation. Here is the initial structure: export interface SearchBarValidatorObj { [k: string]: KeyObjectValidator; } However, I am wondering if there is a way to add a "static" type to it in order to achieve ce ...