如何访问异步获取函数的值? [英] How can I acces the values of my async fetch function?
问题描述
我想在另一个函数中使用获取的值
I want to use my fetched values in another function
我真的是JS新手.所以直到现在我都尝试了this.setState()和该函数的返回值.
I'm really new to JS. So until now I tried this.setState() and a return value of the function .
async fetchData() {
const url = 'http://localhost:8080';
const response = await fetch(url);
const data = await response.json();
// stringify JSON
var myJSON = JSON.stringify(data);
// parsing to JS object
var jsonData = JSON.parse(myJSON);
}
直到现在,我得到一个状态为"pending"的Promise.如何获得实际值?
until now, I'm getting a Promise with the status "pending" . How do I get the actual value?
推荐答案
When you mark the function as async
that implicitly wraps any return value it has with a Promise. You're not actually returning anything, so fetchData
will just return a Promise that resolves to undefined
.
因此,首先,您需要从函数中实际返回一些内容:
So first, you need to actually return something from your function:
async fetchData() {
const url = 'http://localhost:8080';
const response = await fetch(url);
const data = await response.json();
return data; // It should already be parsed JSON since you called `response.json()`
}
然后,您需要等待Promise在调用函数中完成:
Then you need to wait for the Promise to complete in the calling function:
// You can use async/await
async someOtherFunction() {
const value = await fetchData();
// Do things...
}
// Or use .then
someOtherFunction() {
fetchData().then((value) => {
// Do things...
});
}
这篇关于如何访问异步获取函数的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!