-2

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)

1
  • Could you please edit your question and add more info? What you are looking for? What have you tried?
    – SrArkaitz
    Sep 27, 2021 at 8:09

1 Answer 1

0

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);
     });
  }
})

; })

Not the answer you're looking for? Browse other questions tagged or ask your own question.