hussain
hussain

Reputation: 7123

Do we need to wrap return value into promise using async/await?

Just wanted to understand correct approach using async/await when we return the value in async functions. what would be correct way to write code for async functions and return the value with promise ?

main.ts

private async customerResponse(data: any): Promise < any > {

    const custObject: any = data;

    Promise.resolve(custObject);
    Or 
    return custObject;


}

Upvotes: 3

Views: 1823

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191789

An async function returns a promise. Moreover, you only need to use async if you need the await keyword. If you're not using await, don't use async.

The return value of an async function is effectively unwrapped to a single level when using Promise.resolve (I think this is part of Promise.resolve functionality), so there is no difference between returning Promise.resolve(value) or just returning value (or Promise.resolve(Promise.resolve(value)) for that matter). That said, you should simply return the desired return value from async functions and not worry about doing any additional wrapping.

Upvotes: 11

Related Questions