首页 > 解决方案 > 如何访问从 API 调用返回的该对象内部的值

问题描述

带有 console.log 的图像

我想访问和打印对象“命中”的信息

这是我的代码:

export async function fetchData(searchValue) {
    await fetch(`https://api.edamam.com/search?q=${searchValue}&app_id=${apiId}&app_key=${apiKey}`)
        .then(response => response.json())
        .then((res) => {return res;});
}

标签: javascriptreactjsapiobject

解决方案


如果您想直接从该函数返回数据,请使用

export async function fetchData(searchValue) {
  return await fetch(
    `https://api.edamam.com/search?q=${searchValue}&app_id=${apiId}&app_key=${apiKey}`
  )
    .then((response) => response.json());
}

现在调用该方法时,要么使用 async/await 要么.then记录

// async/await (inside of an async function)
const result = await fetchData('something');
console.log(result.hits);

// `.then`
fetchData('something').then(result => console.log(result.hits));

推荐阅读