【问题标题】:How to I access the value in the [[PromiseResult]] from axios?如何从 axios 访问 [[PromiseResult]] 中的值?
【发布时间】:2021-08-31 21:35:52
【问题描述】:

我使用 Axios 并从 'data.json' 文件中获取数据。

const RoomItems = axios.get("./data.json")
.then((res) => { return res.data })
.catch(() => { console.log('fail') })

在 console.log 之后像 console.log(RoomItems) , 结果如下所示

Promise
  __proto__: Promise
  [[PromiseState]]: "fulfilled"
  [[PromiseResult]]: Array(3)

如何访问 [[PromiseResult]] 中的 value(=Array(3)) ? 我尝试了各种方法来获取这个值,Array.但我做不到。

我想使用map(),但我不能,因为我无法在 [[PromiseResult]] 访问这个数组。

【问题讨论】:

  • 可以直接导入JSON文件使用。不需要 axios。
  • const RoomItem = require('./data.json'); console.log(RoomItem);

标签: promise axios


【解决方案1】:

RoomItems 是 Promise,这就是它显示的原因,如果您想要结果,请使用 async/await。

async function abc() {
  const RoomItems = await axios
    .get("./data.json")
    .then((res) => {
      return res.data;
    })
    .catch(() => {
      console.log("fail");
    });

    console.log(RoomItems);
}

const RoomItem = require('./data.json'); 
console.log(RoomItem);

【讨论】:

  • 感谢您的详细解释!我将尝试使用 async/await。谢谢
猜你喜欢
  • 2022-11-29
  • 2022-09-24
  • 2020-10-02
  • 2017-11-18
  • 2020-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-13
相关资源
最近更新 更多