我想在另一个函数中使用获取的值
我对JS真的很陌生。所以直到现在我尝试了 this.setState() 和函数的返回值。
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);
}
到目前为止,我收到的 Promise 状态为 "pending" 。我如何获得实际值?
当您将函数标记为async https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function它隐式地用 Promise 包装了它所具有的任何返回值。你实际上并没有返回任何东西,所以fetchData
只会返回一个 Promise 来解决undefined
.
因此,首先,您需要从函数中实际返回一些内容:
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完成:
// You can use async/await
async someOtherFunction() {
const value = await fetchData();
// Do things...
}
// Or use .then
someOtherFunction() {
fetchData().then((value) => {
// Do things...
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)