取消Fetch API請求

     現在,Fetch API已經成爲如今瀏覽器異步網絡請求的標準方法,但Fetch也是有弊端的,好比: Fetch尚未方法終止一個請求,並且Fetch沒法檢測上傳進度json

     如今咱們能夠經過 AbortControllerAbortSignal 來終止,代碼以下:     promise

          const controller = new AbortController()瀏覽器

          const signal = controller.signal網絡

          fetch('./data.json', { signal })異步

      能夠經過controller.abort()來通知終止事件,好比,你能夠在請求發出後3秒來終止請求fetch

      setTimeout(() => { controller.abort(); }, 3 * 1000);spa

 

      若是請求完成了,調用absort()不會發生錯誤事件

      若是請求沒有完成,那麼Fetch就會拋出一個DOMException異常,異常的name屬性值爲"AbortError",能夠在promise中的catch捕獲這個異常io

     例如:  fetch('./data.json', { signal })console

                  .then((res) => {})

                  .catch((err) => {

                     if (err.name === 'AbortError') {

                         console.log('Fetch aborted');

                    } else {

                        console.log('Another error');

                   }

                 })

相關文章
相關標籤/搜索