How do you return anything from async functions? How do you receive what is returned from async functions?
Previously we have seen how return
works in Javascript. I typically write functions that return at least a true
or false
value.
1
2
3
4
5
6
7
8
9
10
11
12
|
function printThis(statement) {
console.log(statement);
return true;
}
const ret = printThis("hello world");
console.log(ret);
/* output
hello world
true
*/
|
If the function described above is async -
1
2
3
4
5
6
7
8
9
10
11
12
|
async function printThis(statement) {
console.log(statement);
return true;
}
const ret = printThis("hello world");
console.log(ret);
/* output
hello world
Promise { true }
*/
|
If you are interested in the return value from an async function, just wait till the promise resolves. Use then
or wrap function in await
.
1
2
3
4
5
6
7
8
9
10
11
|
async function printThis(statement) {
console.log(statement);
return true;
}
const ret = printThis("hello world").then(ret => console.log(ret));
/* output
hello world
true
*/
|
Also see