简体   繁体   English

获取纯 javascript 处理承诺

[英]fetch pure javascript handling promises

    return fetch(url)
    .then(response => response.json())
    .then(json => {
        //everything just here?
    })
    .catch(err => console.log(err));

Hello guys i have a newbie question.大家好,我有一个新手问题。 If i want to get some data from server and manage them (create new html elements, draw some canvas) am i forced to do it this way in ".then" chain?如果我想从服务器获取一些数据并管理它们(创建新的 html 元素,绘制一些画布)我是否被迫在“.then”链中这样做? Im asking because its quite unintuitive.我问,因为它很不直观。 And ill be glad for some example of code like this, just get data from server and create/edit some html elements.对于这样的代码示例,我会很高兴,只需从服务器获取数据并创建/编辑一些 html 元素。 Thanks!谢谢!

You can do it in more intuitive way like this您可以像这样以更直观的方式进行操作

getDataFromServer(url) {
    return fetch(url)
    .then(response => response.json());
}

async yourMainFunction() {
    const data = await getDataFromServer(url);
    ////everything just here with data from server? 
}

one thing to note that for using await you have to make your function marked with async需要注意的一件事是,使用 await 你必须让你的 function 标记为 async

You are correct, the only place the response json is avalable is in the second then() callback.你是对的,响应 json 可用的唯一地方是第二个then()回调。

You could create a function that contains your html/canvas logic and then call that function in the response callback.您可以创建一个包含您的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM