wait for response from api for 5 sec if response taking time put in console log

Issue

IF api taking time then it should notify within 5 sec

const result = await API.methodForAPI()

// if Noresponse from API in 5 sec show alert
if(result)

Solution

You can try with Promise.race, to find what returns first, the API call or the 5 sec timeout.

var p1 = fetch('https://reqres.in/api/users?page=2');
var p2 = new Promise((resolve,reject)=>{ setTimeout(resolve, 5000, new Error('timeout'))
var p1 = fetch('https://reqres.in/api/users?page=2')
var p2 = new Promise((resolve,reject)=>{ setTimeout(resolve, 5000, new Error('timeout')); });

Promise.race([p1,p2]).then((res)=>{
  if(res instanceof Error) {
      console.warn(res);
  } else {
     res.json().then((users)=> {
         console.log(users);
     });
  }
})

; })

Answered By – Nice Books

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published