简体   繁体   中英

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.

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

Well at first we need to declare a variable let's say temp. Then use fetch API to request our query with URL. If server status is 200 then it will return a promise, we need to use then method by passing any argument (res, response, r anything...) and then a fat arrow function ( => ) so that we can make the response as json format. After then we need to use another then method to return the json output and assign the value to our declared temp variable.

But if there is any error like 500, 400, 404 server error we need to use catch method with err argument and console it out.

let temp;

fetch('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo')
    .then(res => res.json())
    .then(data => temp = data)
    .catch(err => console.log(err));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM