0

There's probably an obvious mistake somewhere, but I just can't out find what's wrong.

I'm trying to retrieve data from an api, and use the js-function below to get it. If I do an alert(key) on the data inside the $.get-function, it alerts the correct data.

function getApiKey(company, password) {
    var url = "http://myapi.com/" +company+ "?password=" +password;
    var key = "";

    $.get(url).done(function(data) {
        key = data;
        //alert(key) returns the correct data
    });

    return key;
}

However, I need to use the function in a different file, and that's where it doesn't work. When I do

    var key = getApiKey("company", "password");
    alert(key);

key is empty.

asontu
  • 4,548
  • 1
  • 21
  • 29
msk
  • 1,052
  • 3
  • 15
  • 31
  • 1
    You can't do it like that. [This answer explains why and shows some solutions](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Spokey Feb 23 '15 at 14:18

1 Answers1

2

The $.get command is asynchronous, meaning that your function returns key with its initial value of "", then later when the async callback fires, it runs key=data.

You should read up on asynchronous behaviour in javascript - for a solution, you'll need some way to get the data back to the place of the call asynchronously. One such option is a promise.

doldt
  • 4,466
  • 3
  • 21
  • 36