JavaScript alerts the value before returning function has finished the API query

function Function1() {
    $.get(_VALID_GET_LINK_)
    .done(function(answer) {
        alert(answer);   // Expected answer
        return answer;
    })
    .fail(function(answer) {
        alert("Error: " + answer);
    });
};

function Function2() {
    var1 = Function1();
    alert(var1);   // undefined
}

$(_SOME_SELECTOR_).keypress(function (key){
    if (key.which == 13) {
        EngineWorker();
    }
});

What is happening essentially is. Function2 requests value from Function1, but Function1 doesn’t have any value except when AJAX request is being done, by the time that Function1 is able to return answer. Function2 has already alert() or assigned the variable, which is undefined. Could someone help me come up with the solution?

I’m probably going around with this the wrong way. But that’s why you’re here guys, to help people like me, learn these things up. So. Where did I screw up?

(I stripped some variables but I do initialize them, the REST API is working as alert(answer) produces expected output)

Yep, you want to return the Promise from Function1, then you can wait for it to complete in Function2 before using it.

function Function1() {
  return $.get(_VALID_GET_LINK_)
  .then(function(answer) {
    return answer;
  })
  .catch(function(err) {
    alert("Error: " + err);
  });
};

function Function2() {
  var promise = Function1();
  promise.then(function(answer) {
    alert(answer); // Expected answer
  })
}

then / catch are the functions typically used with Promises.
There’s no point of this function either:

.then(function(answer) {
  return answer;
})

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.