API以承诺方式返回数据,但不能转换为字符串

时间:2018-06-20 22:13:20

标签: javascript json api

我正在尝试获取外部API的项目,尽管结果显示在控制台中,但在尝试提取数据并将其解释为HTML输出时遇到了一些麻烦。

我创建了一个名为makeRequest的常量,例如,当我尝试将其转换为字符串或使用innerHTML提取到类中时,会从API中提取数据,我会得到“对象承诺”或未定义。

我很困惑。有任何想法吗?我确定我缺少明显的东西,但是我已经很长时间没有练习JS了。

编辑:我能够将数据返回到控制台日志,但是我无法获得该响应以成为字符串并解析为HTML

https://codepen.io/iambeeroy/pen/dKJjQw

    //Request is defined and
const request = options => {
  return fetch(options)
    .then((response) => {
        return response.json();
    })       
    .then((data) => {
        return data;
    })
    .catch(error => console.error(error));
};

//Logs the request in the console
const makeRequest = request('https://api.punkapi.com/v2/beers?abv_gt=6');
console.log(makeRequest);

var res = makeRequest.toString();
document.getElementById("beers").innerHTML = res;

1 个答案:

答案 0 :(得分:0)

这不是承诺的工作方式。 then()catch()回调中的位在其余代码后 执行。因此,您的makeRequest变量将是Promise对象,并且您不能将其转换为字符串。它实际上不是数据,而是在将来某个时刻交付数据的承诺。

想要处理承诺数据的任何事情都必须在回调内完成,例如:

    //Request is defined and
const request = options => {
  return fetch(options)
    .then((response) => {
        //this gets passed on to other .then() calls
        return response.json();
    })
    .catch(error => console.error(error));
};


const makeRequest = request('https://api.punkapi.com/v2/beers?abv_gt=6')
   .then(data => {
       //this will get the response.json() result from the fetch callback above
       var res = data.toString();
       document.getElementById("beers").innerHTML = res;
   });