Home > OS >  is it necessary to await the result of every async function?
is it necessary to await the result of every async function?

Time:11-09

I've defined the following JavaScript function

async isDataValid (externalValidation = true) {
    const isValid = (await this.v$.$validate()) && externalValidation
    // other stuff not relevant to my question happens here
    return isValid
}

AFAIK, I need to define this as an async function in order to await the result of this.v$.$validate().

Because isDataValid is itself async, I thought I need to use await whenever I call it, but when I did the following:

const result = await this.isDataValid()

My IDE marked this with a warning

Redundant 'await' for a non-promise type

So it seems my IDE is saying that await only needs to be used if an async function returns a promise i.e. there is no need to use await with isDataValid because it returns a boolean.

Does await need to be used when calling all async functions, or only those that return a promise?

Update

I am using JavaScript, not TypeScript

CodePudding user response:

If you put await in front of a non promise, it will be auto wrapped in a promise and the value will be fulfilled (but in the next cycle). The execution order will definitely change.

Does await need to be used when calling all async functions, or only those that return a promise?

Do not think whether await needs to be used when calling all async functions, or only those that return a promise.

async is only used when a function returns a promise. If you are using it for functions that do not return a promise, then you probably do not need it.

I think the IDE is not able to figure out that isValid is actually a Promise. Either explicitly mark the return type like:

async isDataValid (externalValidation = true) : Promise<boolean> {
    const isValid = (await this.v$.$validate()) && externalValidation
    // other stuff not relevant to my question happens here
    return isValid
}

or ignore the warning.

CodePudding user response:

await is not necessary when using async.

Though if you are using async, it is inferred that your function returns a promise.

The async is a function that is bound with a function that function returns the Promise object. The await operator holds the execution of the Promise function as long as the Promise is completely fulfilled.

As your function- isDataValid is not returning a promise in the first cycle, IDE marks the await as redundant.

The solution here is to return a promise from isDataValid function. Give the return type of isDataValid as Promise<Boolean> and make sure you in-real return a promise.

  • Related