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>
?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With