2 years ago

#64786

test-img

user5969116

Swapping from XMLHttpRequest() to Fetch() and still get boolean output

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!

javascript

xmlhttprequest

fetch

output

undefined

0 Answers

Your Answer

Accepted video resources