Search code examples
javascriptpromisees6-promise

Return data from Promise and store it in variable after API Call


I´m pretty new to Promises and found many examples here how to access the actual value which is always done with console.log. But my goal is to store the result in a variable and work with it.

getdata = () =>
  fetch(
    "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo"
  )
    .then(response => {
      if (response.status === 200) {
        return response.json();
      } else {
        throw new Error("This is an error");
      }
    })
    .then(data => {
      console.log(data);
    });

getdata();

This code works. Can you help me to rewrite it that the getdata() function allows me to store the result in a variable. Return does not work since I will receive another pending Promise.


Solution

  • You can do it like this:

    getdata = () =>
      fetch(
        "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo"
      ).then(response => {
        if (response.status === 200) {
          return response.json();
        } else {
          throw new Error("This is an error");
        }
      });
    
    getdata().then(data => {
      //I can do whatever with data
    });
    

    Of course you would also want to handle the scenario where the request failed, so you could also chain a .catch(). Alternately, if you have your build process configured for it, you can use async and await so you could do:

    try {
      const data = await getdata();
    } catch(err) {
    }
    

    This would need to be in a function marked as async