javascript - 如何访问我的异步获取函数的值?
问题描述
我想在另一个函数中使用我获取的值
我对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);
}
到目前为止,我收到了一个状态为 "pending" 的 Promise。我如何获得实际价值?
解决方案
当您将函数标记为async
隐式包装它具有 Promise 的任何返回值时。你实际上并没有返回任何东西,所以fetchData
只会返回一个解析为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...
});
}
推荐阅读
- ios - react-native-youtube 当手机处于静音模式时没有视频声音
- mysql - Sql 在仍然拥有所有行值的同时计算出现次数
- javascript - React-native 找不到变量 简单js学习
- python - 如何在 Pandas 的所有适用行中复制 groupby 的平均值
- python - Python 项目:创建一个程序来跟踪向导可以携带的项目
- python - 我的多行列表合并不断出现此错误
- objective-c - 找不到适合 libswiftAVFoundation.dylib 的图像。代码签名无效
- javascript - AgGrid rowData 未在 Observable 对象的“订阅”调用中更新
- r - R - 将日期值转换为正整数
- mysql - 通过 Ansible (Debian) 安装 MySQL