2

I am trying to understand why promise is not resolved when I am using async and await keywords. Below is the code that I have

var a = 'https://jsonplaceholder.typicode.com/posts';

async function fetchData() {
    const response = await fetch(a);
    const data = await response.json();
    return data;
}
console.log(fetchData());

fetchData function should return actual datas but it always returns a promise object. What am I doing wrong?

I am expect the following output [{userId: 1, name: 'ss'}]after invoking fetchData()

sajan
  • 1,355
  • 1
  • 14
  • 19
  • 1
    `async` functions always return promises, so your statement that "fetchData function should return actual datas" is wrong. You need to obtain the promise's value either by using `then` with a callback or by calling `fetchData` from within an `async` function and `await`ing it. – JLRishe May 19 '18 at 14:09
  • then what is `await` keyword is for? – sajan May 19 '18 at 14:10
  • It allows you to not have to worry about promises _inside the function_. It's why you're able to use `response` on the second line of the function rather than having to do `fetch(a).then(response => response.json())` – JLRishe May 19 '18 at 14:11
  • `console.log(await fetchData())` – Jonas Wilms May 19 '18 at 14:12
  • @JonasW. It will throw a syntax error. – sajan May 19 '18 at 14:25
  • Cause it has to be inside of an `async function`. – Jonas Wilms May 19 '18 at 14:27
  • What happens when you execute an asynchronous function? Nothing, it just promises something at a later point in time which is represented by the Promise object you get. – Nishant May 19 '18 at 14:51
  • The async is used with a function to makes it into an asynchronous function. The await keyword is used to invoke an asynchronous function synchronously. The await keyword holds the JS engine execution until promise is resolved. We should use async & await only when we want the result immediately. Maybe the result is being returned from the function or getting used in the next line. [Follow this blog, It is very well written in simple word][1] [1]: https://www.ui-dev.in/2021/02/async-await-in-javascript-when-to-use.html – Raj Rj Feb 11 '21 at 13:41

1 Answers1

2

The way async works is that it returns a promise. So what you can do is:

fetchData().then(data => console.log({data}))

And you'll print out your data!

Also, you don't need that line:

const data = await response.json();

because the .json() method is synchronous, and thus there's no need to wait for a promise to be resolved.

So a simpler way to do it would be:

var a = 'https://jsonplaceholder.typicode.com/posts';

async function fetchData() {
    const response = await fetch(a);
    data = response.json();
    // do stuff with data, synchronously
    return data;
}

so you want to write code without callbacks, but then what you need is to use fetchData() in an async context, so here's how you can do that:

async function asyncPrint(aPromise) {
    console.log(await aPromise);
}

asyncPrint(fetchData);

and if you're evil, you could do:

console.asyncLog = asyncPrint;

so you can run:

console.asyncLog(fetchData());
zmo
  • 24,463
  • 4
  • 54
  • 90
  • I don't want to do it like `fetchData().then(data => console.log({data}))` I want something like `fetchData()` [{'userId': 1, 'name': 'ss'}] How do i do that? – sajan May 19 '18 at 14:34
  • @sajankumarvijayan Then you're out of luck. If you want to perform asynchronous actions (and making an HTTP request is an asynchronous action), you need to understand how to work with asynchronous code. – JLRishe May 19 '18 at 14:41
  • @sajankumarvijayan I updated my answer to show you how. Basically, you cannot `await` in a non `async` context, but you can create a function that will handle that for you. – zmo May 19 '18 at 14:44