1

Doing just a simple function:

 async function doAsync() {
 return await "test"
 }
 console.log(doAsync())

Output: Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}

What could be wrong?

Niladri Basu
10.7k7 gold badges59 silver badges65 bronze badges
asked Nov 13, 2017 at 8:33
2
  • There is nothing wrong, that is exactly what an async function does, it returns a promise Commented Nov 13, 2017 at 8:35
  • 6
    Nothing is wrong, this is correct, it's a promise. You probably want to read a little about what promises are and how to work with them, before even jumping to async/await. doAsync().then((result) => console.log(result)). Commented Nov 13, 2017 at 8:35

1 Answer 1

3

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.

answered Nov 13, 2017 at 8:57
Sign up to request clarification or add additional context in comments.

3 Comments

Well, I thought the main idea of async/wait to return an actual value to a variable. I used the promises but it doesn't any sense for me then, why would we need async/wait if we have to use promises again. Thanks
@chic_cat - I can't really explain what 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.
Ok, gotcha. Thanks!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.