kotyara85
kotyara85

Reputation: 325

js async/await return promise

Doing just a simple function:

 async function doAsync() {
 return await "test"
 }

 console.log(doAsync())

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

What could be wrong?

Upvotes: 1

Views: 1548

Answers (1)

jfriend00
jfriend00

Reputation: 707148

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.

Upvotes: 3

Related Questions