0

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?

Anup Deuja
  • 43
  • 7
  • 2
    make sure that `GetImageSku` actually *returns* something (it doesn't). So `return this.isImage(imageUrl).then...`. And then you will get a promise, where again you'll have to chain a `then` callback in order to deal with that value *in the future*. – trincot Apr 15 '21 at 18:40
  • 1
    @trincot Thank you so much. That's the exact answer I was looking for. – Anup Deuja Apr 15 '21 at 19:07

0 Answers0