vue.js - 即使 console.log 显示该值,也未定义 Fetch Promise
问题描述
我目前正在尝试从 API (AlphaVantage) 获取一些数据并将数据作为参数传递给 axios.post 到我的 MongoDB,但我收到错误消息说变量未定义,即使我可以使用控制台日志。
static insertPost(shareName) {
axios.get(url)
.then(res => {name = res.data['Meta Data']['2.Symbol'];
console.log(res.data['Time Series (15min)']['2019-08-02 15:45:00']['1.
open']);
price = res.data['Time Series (15min)']['2019-08-02 15:45:00']['1. open'];
})
.then( res => {
return axios.post(url, {
name,
price
})});}
收到此错误:
Uncaught (in promise) ReferenceError: price is not defined at eval
即使名称和 console.log 工作正常,因为它们在第一个承诺中,我不知道发生了什么,有什么建议吗?
解决方案
name
并且price
属于不同的范围。要将其传递给下一个链.then
,您需要返回值
static insertPost(shareName) {
axios.get(url)
.then(res => {
const name = res.data['Meta Data']['2.Symbol']
console.log(res.data['Time Series (15min)']['2019-08-02 15:45:00']['1.open']);
const price = res.data['Time Series (15min)']['2019-08-02 15:45:00']['1. open'];
return { name, price }
})
.then(res => {
return axios.post(url, {
name: res.name,
price: res.price
})
});
}
推荐阅读
- ruby-on-rails - Rails:如何根据 foriegn_key 自动循环创建项目
- maven - 从 maven 模块创建一个 jar 文件
- javascript - 一个只有变量名的语句在 JavaScript 中能做些什么吗?
- kotlin - Kotlin Coroutines:暂停后续访问令牌更新请求
- sql - 从表中更新顶级注册表
- swift - 如何在 SWIFT 中获得小数点后两个数字的精度但不四舍五入
- java - 没有用于创建 Stripe 订阅的附加付款来源
- php - 从另一个 PHP 文件中获取一个 PHP 文件的回显内容
- python - 绘制熊猫数据框日期
- android - 在 Android 应用程序中单击按钮时显示我的位置