plumbe0
plumbe0

Reputation: 107

Can't return JSON field from Fetch response.json() (but can see it from console.log)

I'm developing a Chrome extension and in my background.js i have a function

async function getData() {
  var resp = await (await fetch("https://www.example.com/json")).json();
  console.log(resp.field);
  alert(resp.field);
  return resp.field;
}

When i call the function (var x = getData()) alert and console.log show the content of the field (expected behavior), but then it returns a resolved Promise object. What am i missing?

Upvotes: 0

Views: 717

Answers (1)

kuzyn
kuzyn

Reputation: 1995

Async functions always return promises. Your getData function simply wraps resp.field into a resolved promise.

getData().then(field => console.log(field))

Upvotes: 1

Related Questions