」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 當您不需要時取消獲取請求的簡單方法

當您不需要時取消獲取請求的簡單方法

發佈於2024-08-28
瀏覽:217

The Easy Way to Cancel Fetch Requests When You Don’t Need Them

在本部落格中,我將引導您完成使用 JavaScript 取消提取請求的實際步驟,並專注於 AbortController API。最後,您將清楚地了解如何使您的網頁應用程式更具響應性和資源友善性。

為什麼需要取消獲取請求?

取消獲取請求在以下場景中至關重要:

  • 使用者體驗:當使用者離開頁面時,無需繼續取得該頁面的資料。

  • 搜尋優化:在每次按鍵都會觸發請求的搜尋功能中,在發送新請求之前取消先前的請求會更有效。

  • 逾時場景: 如果出現網路延遲或長時間運行的請求,您可能需要設定逾時並在超過一定持續時間時取消請求。

了解 AbortController

AbortController API 提供了一種優雅的方式來取消獲取請求。它的工作原理是創建一個 AbortController 實例,該實例的訊號被傳遞到獲取請求。如果您在控制器上呼叫 abort() 方法,它將取消請求。

取消取得請求的逐步指南

1。使用 AbortController 的基本設定

讓我們從最基本的範例開始:建立 AbortController 並取消取得請求。

// Step 1: Create an instance of AbortController
const controller = new AbortController();

// Step 2: Pass the signal to the fetch request
fetch('https://jsonplaceholder.typicode.com/posts', { signal: controller.signal })
    .then(response => response.json())
    .then(data => console.log('Data:', data))
    .catch(err => {
        if (err.name === 'AbortError') {
            console.log('Fetch request was canceled');
        } else {
            console.error('Fetch error:', err);
        }
    });

// Step 3: Cancel the fetch request
controller.abort();

2.實際用例:取消使用者互動請求
常見的情況是取消提取請求以響應用戶互動。例如,在實作搜尋功能時,每次按鍵都可能觸發新的獲取請求。取消先前的請求可防止處理過時或不相關的資料。

let controller;

function search(query) {
    // Cancel the previous request if it exists
    if (controller) {
        controller.abort();
    }

    // Create a new controller for the new request
    controller = new AbortController();

    // Fetch data with the new controller
    fetch(`https://jsonplaceholder.typicode.com/posts?query=${query}`, { signal: controller.signal })
        .then(response => response.json())
        .then(data => console.log('Search results:', data))
        .catch(err => {
            if (err.name === 'AbortError') {
                console.log('Previous request canceled');
            } else {
                console.error('Fetch error:', err);
            }
        });
}

// Example usage: simulate user typing
search('React');
search('Vue'); // The request for 'React' is canceled

3.實現獲取請求逾時
在處理不可靠的網路條件時,超時至關重要。使用AbortController,您可以輕鬆實現逾時機制,如果取得請求時間過長,則取消獲取請求。

function fetchWithTimeout(url, timeout = 5000) {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);

    return fetch(url, { signal: controller.signal })
        .then(response => {
            clearTimeout(timeoutId);
            return response.json();
        })
        .catch(err => {
            if (err.name === 'AbortError') {
                console.log('Fetch request timed out');
            } else {
                console.error('Fetch error:', err);
            }
        });
}

// Example usage
fetchWithTimeout('https://jsonplaceholder.typicode.com/posts', 3000)
    .then(data => console.log('Data:', data));

優雅地處理獲取請求取消

取消獲取請求時,優雅地處理它們很重要。這涉及區分由取消引起的錯誤和其他類型的錯誤。

fetch(url, { signal: controller.signal })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(err => {
        if (err.name === 'AbortError') {
            // Handle cancellation specifically
            console.log('Request was canceled');
        } else {
            // Handle other types of errors
            console.error('Request failed', err);
        }
    });

版本聲明 本文轉載於:https://dev.to/rigalpatel001/the-easy-way-to-cancel-fetch-requests-when-you-dont-need-them-1d3g?1如有侵犯,請洽study_golang@163 .com刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3