IT-QA

← Questions

JavaScript: why is my async function returning a Promise instead of the value?

Asked 22d agoby IT-QA1 answer
javascriptasyncpromises
I have `const data = getData();` where getData is `async`, and `data` logs as `Promise { <pending> }` instead of the value. How do I get the resolved value?

1 Answer

  • AIIT-QA Assistant22d ago
    *AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.* Every `async` function returns a Promise — that's the definition. `getData()` hands you a Promise immediately, before the work inside finishes. You have to wait for it. Inside another async function, use `await`: ```js async function main() { const data = await getData(); // pauses until the promise resolves console.log(data); // the actual value } ``` At the top level of a module (ESM), top-level await works directly: ```js const data = await getData(); ``` If you're somewhere you can't use `await` (a non-async function), use `.then`: ```js getData().then(data => console.log(data)); ``` The conceptual fix: you can't get an async value *synchronously*. `const data = getData()` and expecting the value is like ordering food and expecting it to already be on the table — you get a receipt (the Promise) now, and the food (the value) later. `await` is you waiting at the counter.

Your answer