Reputation: 2867
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.
Upvotes: 0
Views: 1761
Reputation: 42
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));
Upvotes: 0
Reputation: 6482
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
Upvotes: 2