首页 > 解决方案 > 即使 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 工作正常,因为它们在第一个承诺中,我不知道发生了什么,有什么建议吗?

标签: vue.jsfetch

解决方案


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
      })
    });
}

推荐阅读