fetch學習

window.fetch

fetch 的基本使用

fetch 是全局量 window 的一個方法, 第一個參數是URL:異步

//url (必須), options (可選)
fetch('/some/url', {
    method: 'get'
}).then(function(response) {

}).catch(function(err) {
    // 出錯了;等價於 then 的第二個參數,但這樣更好用更直觀 
});

fetch API 也使用了 JavaScript Promises 來處理結果/回調:fetch

// 對響應的簡單處理
fetch('/some/url').then(function(response) {

}).catch(function(err) {
    // 出錯了;等價於 then 的第二個參數,但這樣更直觀
});

// 鏈式處理,將異步變爲相似單線程的寫法: 高級用法.
fetch('/some/url').then(function(response) {
    return //... 執行成功, 第1步...
}).then(function(returnedValue) {
    // ... 執行成功, 第2步...
}).catch(function(err) {
    // 中途任何地方出錯...在此處理 :( 
});
相關文章
相關標籤/搜索