当我运行此文件时,我什么也没得到。如果我在最后运行console.log(getInfo());,我会得到Promise <pending>。请帮忙。

function getInfo(){
    var url = `https://api.nutritionix.com/v1_1/search/cheddar%20cheese?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=${apiId}&appKey=${apiKey}`;
    return(
    fetch(url)
    .then(data=>{

        return JSON.parse(data);
     })
    );
}

getInfo().then(result =>{
    console.log(result);

最佳答案

这不是您使用fetch API的方式。像这样使用response.json()(因为我不知道apiIdapiKey,所以会记录错误):



function getInfo(){
  var apiId = 1;
  var apiKey = 1;
  var url = `https://api.nutritionix.com/v1_1/search/cheddar%20cheese?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=${apiId}&appKey=${apiKey}`;
  return fetch(url).then(response => response.json());
}

getInfo().then(data => console.log(data));

10-06 15:16