How to set timeout in the fetch function in react native

时间:2018-09-19 08:23:06

标签: ajax reactjs react-native fetch

I have a fetch function as following:

RequestLogin(params){
 let {username,password}=params;
 try{
   let response = fetch('URL',{
     method:'POST',
     headers:{
      'Accept' : 'application/json',
      'Content-Type' : 'application/json'
     },   
     body:JSON.stringify({
      username,
      password
     })
    }).then(response => response.json()).then(responseJson=> {
       console.log(responseJson);
     })
    } catch(error){
       console.log(error);
    }

I want to know how can I set a timeout to that?

Thanks, advance.

1 个答案:

答案 0 :(得分:2)

You can make a promise that could be awaited as

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

and when you call your function that uses a fetch function as you have provided above

// Inside some async wrapped func
    await timeout(4000);
    await RequestLogin(params)