username
username

Reputation: 159

Return data from a pending promise

Trying to store the response into a variable. Not sure what I'm doing wrong. Any help would be appreciated.

async function fetchData(url) {
  const response = await fetch(url);

  if (!response.ok) {
    const message = `An error has occured: ${response.status}`;
    throw new Error(message);
  }

  const data = await response.json();
  return data;
}

async function getActivities() {
  let response = null;
  try {
    response = await fetchData("https://www.boredapi.com/api/activity");
    return response;
  } catch (error) {
    throw error;
  }
}

let data = getActivities();
console.log(data);

Upvotes: 1

Views: 62

Answers (2)

TimoStaudinger
TimoStaudinger

Reputation: 42460

You will have to wait for the promise returned from getActivities to resolve. Since you marked that funcition as async, it will return a promise that resolves to the function's return value.

For example:

getActivities()
    .then(data => console.log(data));

Alternatively, wrap your application logic into an async function, which would allow you to use await:

async function main() {
  let data = await getActivities();
  console.log(data);
}
main();

Once top level awaits are a thing, wrapping your logic in a main function will be unnecessary.

Upvotes: 1

Tushar Shahi
Tushar Shahi

Reputation: 20376

Using the same logic you used inside your functions, console.log() would execute well before your data is returned.

You can use a .then()

getActivities().then(data => 
{ console.log(data);
});

Or if you want to go with another async/await

(async randomFunction() {
let data = await getActivities();
console.log(data);
}());

Upvotes: 0

Related Questions