簡體   English   中英

獲取純 javascript 處理承諾

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM