[英]fetch pure javascript handling promises
return fetch(url)
.then(response => response.json())
.then(json => {
//everything just here?
})
.catch(err => console.log(err));
大家好,我有一个新手问题。 如果我想从服务器获取一些数据并管理它们(创建新的 html 元素,绘制一些画布)我是否被迫在“.then”链中这样做? 我问,因为它很不直观。 对于这样的代码示例,我会很高兴,只需从服务器获取数据并创建/编辑一些 html 元素。 谢谢!
您可以像这样以更直观的方式进行操作
getDataFromServer(url) {
return fetch(url)
.then(response => response.json());
}
async yourMainFunction() {
const data = await getDataFromServer(url);
////everything just here with data from server?
}
需要注意的一件事是,使用 await 你必须让你的 function 标记为 async
你是对的,响应 json 可用的唯一地方是第二个then()
回调。
您可以创建一个包含您的 html/canvas 逻辑的 function,然后在响应回调中调用该 function。
fetch(url)
.then(response => response.json())
.then(json => {
handleResponse(json) // ⭐️
})
.catch(err => console.log(err));
function handleResponse (json) {
// ⭐️ everything in here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.