1

I'm using ajax to make a request for an img via an external url. Using return(url) gives me the result I'm looking for but when doing this through the promise I don't. When logging the url I get the image data. I'm not worried about CORS as the header has been allowed via the server.

getProductImg: function(id) {
    var url = 'https://test' + id;
    return(url); //This gives me the result I want, but I'm looking to do this through the request below.

    $.get(url, function() {
        console.log('request has been made');
    }).done(function(url) {
        console.log('url' + url);
        return (url);
    }).fail(function() {
        alert( "error" );
    }).always(function() {
        console.log('something generic here');
    });
}
w3spi
  • 4,380
  • 9
  • 47
  • 80
Pianoc
  • 763
  • 1
  • 11
  • 32

1 Answers1

1

You cannot return the result of an asynchronous operation in this way. You need to rewrite your getProductImg method signature to accept a callback, like this:

getProductImg: function(id, cb) {
    $.get('https://test' + id, function() {
        console.log('request has been made');
    }).done(function(url) {
        // call callback without an error
        cb(null, url);
    }).fail(function() {
        // call callback with an error only
        cb('error');
    });
}

And call it like this:

obj.getProductImg('someId', function(err, url) {
    if(err) {
        console.log(err);
        return;
    }

    // process url here...
    console.log('url: ' + url);
});
sdgluck
  • 24,894
  • 8
  • 75
  • 90
  • Hi @sdgluck I had another question which I have updated with your answer using a cb. I am not sure what would be the best way to call is the way my Service and Directive are set up, would you mind having a look for me? http://stackoverflow.com/questions/32496004/retrieve-an-external-url-via-ajax-or-jquery-and-place-in-angularjs-directive – Pianoc Sep 11 '15 at 10:06