Search code examples
javascriptnode.jses6-promise

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);

Solution

  • 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.