Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a async function which returns Promise<void> have an implicit return at the end of a block?

public async demo(): Promise<void> {
    // Do some stuff here
    // Doing more stuff
    // ... 
    // End of block without return;
}

Is a new Promise<void> returned implicitely at the end of the block in TypeScript/ES6?

Example for boolean type:

class Test {

    public async test(): Promise<boolean> {
        return true;
    }

    public main(): void {

        this.test().then((data: boolean) => {

            console.log(data);

        });

    }

}

new Test().main();

This prints true to the console because a return inside of a async function creates a new Promise and calls resolve() on it with the returned data. What happens with a Promise<void>?

like image 468
Gala Avatar asked May 27 '17 12:05

Gala


People also ask

Do async functions have to return promises?

Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

What does a Promise void return?

When a function definition has a void return type, it means the function must not return anything. If you need to resolve the Promise with a value of another type, pass the specific type to the generic. Copied! The Promise above can only be resolved with a number.

How does async function return a value?

To return values from async functions using async-await from function with JavaScript, we return the resolve value of the promise. const getData = async () => { return await axios.

How do I get the Promise result from async function?

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.


1 Answers

What happens with a Promise

Same thing with a function that returns void. A void function returns undefined. A Promise<void> resolves to an undefined.

function foo(){}; console.log(foo()); // undefined
async function bar(){}; bar().then(res => console.log(res)); // undefined
like image 95
basarat Avatar answered Oct 13 '22 11:10

basarat