After java asynchrony in js is a problem for me. The essence of the problem: write a function that checks for the presence of a file, if there is, then true , no - false . It would seem simple, but it was not there.

Used the deprecated function. And it spawned a lot of code with its use. Now we need to make it so that the same function works the same way, but was implemented differently.

Now my code in if is executed as false , without waiting for the correct answer from doesFileExist(urlToFile); Tell me, how can I screw my legs here? With $.when I can't do anything (

  function doesFileExist(urlToFile) { $.ajax({ url: urlToFile, type: 'HEAD', error: function () { console.log(false) return false; }, success: function () { console.log(true) return true; } }); } if(doesFileExist(url)){} 

old version

  function doesFileExist(urlToFile){ var xhr = new XMLHttpRequest(); xhr.open('HEAD', urlToFile, false); xhr.send(); if (xhr.status == "404") { return false; } else { return true; } } 
  • 2
    Previously, you had a synchronous call, and now it has become asynchronous. return to error and success handlers does not make sense. The code that calls doesFileExist will still have to be redone. - Igor

2 answers 2

The old version is a synchronous code (the main thread will be “frozen” * until the result is obtained). New varaint - asynchronous. And the function doesFileExist after sending asin. the request will return undefined (since when we do not return anything (what happens in success and error , it will be executed later, after receiving the answer), returns undefined )

 doesFileExist() { //async action setTimeout(function(){ return true; }, 0) // return undefined } console.log(doesFileExist()); // undefined 

To process the result, you need to create functions (in this case, two) that will be called when a response is received.

 var successCallback = function() { console.log(true); } var errorCallback = function() { console.log(false); } doesFileExist(url, successCallback, errorCallback); function doesFileExist(urlToFile, success, error) { $.ajax({ url: urlToFile, error: error, success: success }); } 

    Add 2 new parameters to the doesFileExist function, for example, successCallback and failCallback . Instead of return true/false , successCallback()/failCallback() these functions: successCallback()/failCallback() .

    And the final method call will be something like this:

     doesFileExist(url, function() { // файл существует }, function () { // файл отсуствует });