javascript - 从 Promise 返回数据并在 API 调用后将其存储在变量中
问题描述
我对 Promises 很陌生,在这里找到了许多示例如何访问始终使用console.log
. 但我的目标是将结果存储在一个变量中并使用它。
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();
此代码有效。你能帮我重写它,该getdata()
函数允许我将结果存储在一个变量中。Return 不起作用,因为我将收到另一个待处理的 Promise。
解决方案
你可以这样做:
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
});
当然,您还想处理请求失败的情况,因此您也可以链接一个.catch()
. 或者,如果您为其配置了构建过程,则可以使用async
,await
因此您可以执行以下操作:
try {
const data = await getdata();
} catch(err) {
}
这需要在标记为的函数中async
推荐阅读
- swift - 在 iOS 13 中将 UIImagePickerController 导航栏设置为不透明
- java - JavaFX:支持不同的分辨率
- android - RecyclerView adapterNotifychanged 不起作用
- python - 如何将字符串末尾的可选组与正则表达式匹配?
- facebook - okta OAuthError:无法从授权码获取访问令牌
- c# - CSVHelper - 使用两个映射类并根据 csv 文件每一行的字段中的值选择映射
- ios - 我怎样才能把它从swift变成objective-c?
- javascript - 如何将过滤器插入到 graphql 查询字符串中?
- javascript - 使用crypto js AES ECB算法在JavaScript中加密字节数组
- vue.js - NuxtJS 动态路由 SSR