Ben*_*tor 4 javascript http fetch-api
我正在努力从 js 中的 http fetch 获取实际结果数据。我可以使用 XMLHttpRequest 来完成此操作,但我更愿意使用获取。我一直在尝试从这样的获取请求中获取结果:fetch('https://api.website.net/?);
我知道您需要分配一个 then 函数,但我尝试过的任何方法都不起作用,我不断获得更多的承诺对象,但没有结果。我模糊地理解,一旦它解析,您需要分配一个 .then 函数,但我真的不知道如何做到这一点。
(这是在浏览器js中而不是节点中)
Mau*_*rez 11
我认为你对承诺感到困惑。fetch 函数返回一个承诺而不是数据。
我建议您阅读这个现代教程: https: //javascript.info/fetch
这是一个非常简单的函数,它获取 url 并以 json 形式返回响应数据:
async function callApi(url) {
const response = await fetch(url);
const data = await response.json();
return data;
}
let data = await callApi('https://api.website.net/?');
// do whatever you want with the data
Run Code Online (Sandbox Code Playgroud)
处理原语时有两种语法,旧的.then()
和新的async
/ await
。一般来说,使用async
/await
更好async
,因此我建议使用/await
语法。有了.then()
它就会像这样:
// Not recommended alternative
fetch('https://api.website.net/?')
.then(response => response.json())
.then(data => {
// do whatever you want with the data
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7702 次 |
最近记录: |