N
N
newaitix2022-04-21 15:18:33
JavaScript
newaitix, 2022-04-21 15:18:33

Is it possible to make such a function call?

Hello. The idea is to execute an if loop after the request.
What is the correct way to return the test variable so that the if condition will only work after the request has been executed?

async function postData(){
  fetch('/favicon.ico?_=16505383').then(function(res){
    if(res.headers.get('Content-Type').split('/')[0]=='image'){
      var test='test1';
    }else{
      var test='test2';
    }
  }).catch((error) => {
    var test='test1';
  });
  return test;
}
if(await postData()=='online'){
  console.log('online')
}else{
  console.log('offline')
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
newaitix, 2022-04-21
@newaitix

var online=(async()=>{
  if(navigator.onLine){
    var date=+new Date();
    var res=await fetch('/favicon.ico?_='+date);
    var ret=await res.headers.get('Content-Type').split('/')[0]=='image';
  }else
    ret=navigator.onLine;
  return ret;
});
if(await online()==true){
  console.log('online')
}else{
  console.log('offline')
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question