0

I know there's zillions of ways of doing this ...

So I have this function which returns me boolean upon HEAD file check status using XMLHttpRequest.

const urlToFile = "shorturl.at/devIK";
function doesFileExist(urlToFile) {
  let xhr = new XMLHttpRequest();
  xhr.open('HEAD', urlToFile, false);
  xhr.send();
  return xhr.status == "404" ? false : true;
}

However, deprecated.

Now trying to build and understand how to handle data output from fetch API. Turns out I'm not able to get desired output.

const urlToFile = "shorturl.at/devIK";
function doesFileExist(urlToFile) {
  return fetch(urlToFile, { method: 'HEAD' })
   .then(res => { res.ok ? true : false; })
   .then(fileExistResult => fileExistResult.boolValue())
   .catch(err => console.log('Error: ', err));
}

-->

doesFileExist(urlToFile) == true ? do_this : do_that;

I keep getting undefined from console.log If you could help me out on this one... Thanks in advance!

  • Apart from what is actually asked, conditional operator is not purposed to replace `if ... else` structure, it's an operator returning a value, not a control flow statement. – Teemu Jan 18 '22 at 11:16
  • doesFileExist() now returns a Promise, not a Bool value – Luca Kiebel Jan 18 '22 at 11:16

0 Answers0