The following function checks if the given URL is an image.
this.isImage = function (src) {
var deferred = $q.defer();
var image = new Image();
image.onerror = function () {
deferred.resolve(false);
};
image.onload = function () {
deferred.resolve(true);
};
image.src = src;
return deferred.promise;
}
The above function isImage is called from the following function GetImageSku. This function returns the default image if the URL is not an image.
this.GetImageSku = function(imageSku) {
var imageUrl = "https://storage.s3.amazonaws.com/Prod/NONCPE/SKUImages/" + imageSku + ".JPG";
this.isImage(imageUrl).then(function (result) {
if (result == true) {
return imageUrl;
}
else {
imageUrl = "../../../Content/images/cone.png";
return imageUrl;
}
});
};
I'm calling the function like this:
var imageUrl = GetImageSku(imageSku);
Upon executing the application, the imageUrl is set as undefined in above variable. (This is because I believe that isImage is async.) How do I make the function call set in imageUrl wait for the function GetImageSku to finish?