Use a callback, or your own Promise
.
Here's the callback approach:
function ROIFileExists(callback){
// --------------------^ Accept the function to call back as an arg
jQuery.ajax({
type: "POST",
url: "ROIFileExists.php",
data: { FileName: fileName},
cache: false
}).done(function( result ) {
var fileAlreadyExists = (result!==0);
console.log('fileAlreadyExists='+fileAlreadyExists);
callback(fileAlreadyExists);
// ---------^ Call it
});
}
Usage:
ROIFileExists(function(exists) {
console.log("Exists? " + exists);
});
Here's the Promise
approach:
function ROIFileExists(){
var d = new $.Deferred(); // Create the deferred object
jQuery.ajax({
type: "POST",
url: "ROIFileExists.php",
data: { FileName: fileName},
cache: false
}).done(function( result ) {
var fileAlreadyExists = (result!==0);
console.log('fileAlreadyExists='+fileAlreadyExists);
d.resolve(fileAlreadyExists); // <=== Resolve it
});
return d; // <=== Return it
}
Usage:
ROIFileExists().done(function(exists) {
console.log("Exists? " + exists);
});
I would strongly suggest not using async: false
. It leads to a poor user experience, locking up the UI of the browser during the call; it's going to go away in a future version of jQuery (you'd have to use XMLHttpRequest
yourself); and you can't use async: false
if you ever have a similar need but when you're using JSONP.
JavaScript code on browsers is event-driven anyway, so embracing that event-driven nature (in this case, the event being that you get the information back about the file) is usually the way to go.