Doing a Timeout Error with Fetch - React Native

前端 未结 6 1343
春和景丽
春和景丽 2021-02-05 15:50

I have a user login function that is working. But, I want to incorporate a time out error for the fetch. Is there a way to set up a timer for 5 seconds or so that would stop try

6条回答
  •  时光说笑
    2021-02-05 16:11

    // Wrapper function for fetch
    const fetchSomething = async () => {
        let controller = new AbortController()
        setTimeout(() => controller.abort(), 3000);  // abort after 3 seconds
        const resp = await fetch('some url', {signal: controller.signal});
        const json = await resp.json();
        if (!resp.ok) {
            throw new Error(`HTTP error! status: ${resp.status}`);
        }
        return json;
    }
    
    
    // usage
    try {
        let jsonResp = await fetchSomthing();
        console.log(jsonResp);
    } catch (error) {
        if (error.name === 'AbortError') {
            console.log('Network Error');
        } else {
            console.log(error.message);
        }
    }
    

    I think using AbortController is the recommended way to abort a fetch call. The code snippet above handles the following scenarios:

    1. If network is good but HTTP returns an error status, the message "HTTP error! ..." will be logged.
    2. If network is down, setTimeout would trigger the AbortController to abort fetch after three seconds. The message "Network Error" will be logged.
    3. If network is good and HTTP response is good, the response JSON will be logged.

    The documentation for using AbortController to abort fetch is here.

提交回复
热议问题