Doing a Timeout Error with Fetch - React Native

前端 未结 6 1382
春和景丽
春和景丽 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:07

    I have made a ES6 function that wraps ES fetch into a promise, here it is:

    export async function fetchWithTimeout(url, options, timeout = 5000) {
        return Promise.race([
            fetch(url, options),
            new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeout))
        ]);
    }
    

    Here is how to use it:

    const requestInfo = {
        method,
        headers,
        body,
    };
    const url = 'http://yoururl.edu.br'
    let data = await fetchWithTimeout(url, requestInfo, 3000);
    

提交回复
热议问题