Doing just a simple function:
async function doAsync() {
return await "test"
}
console.log(doAsync())
Output: Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
What could be wrong?
1 Answer 1
async functions return a promise. Always. You must use .then() or await on that promise to get the value.
doAsync().then(val => {
console.log(val);
});
While async and await sometimes let you write more synchronous-looking code inside the function itself, they don't fundamentally change asynchronous operations into synchronous ones.
An async function still returns a promise and the only way to get its value is to use .then() or await on it. If you're returning a value up the chain, you will eventually need to use .then() to get the value.
See the MDN description for an async function. Here's a quote:
Return value
A Promise which will be resolved with the value returned by the async function, or rejected with an uncaught exception thrown from within the async function.
3 Comments
await is useful for here in a comment (that's a longer article), but I find it most useful when there are multiple asynchronous functions that you want to run serially within a function. I'd suggest you read some of the hundreds of tutorials on async/await on the web. It does not turn an async function into a non-async function. You can't do that in Javascript.
doAsync().then((result) => console.log(result)).