-2

I have a situation where I need to get a value from ajax call, then pass that value to a callback function. Just like this:

function getValue(callback){
    var val = getfromajax();
    //need to return value and then execute the callback here
    return val;
    callback();
}

var myval = getValue(function(){
    alert(myvalue)
})

In the example above in the functon showValue I need to call getValue and use the returned value and pass it to callback function (which alerts it).

Is there a way to do that?

Lamar
  • 1,761
  • 4
  • 24
  • 50
  • 1
    Is `getfromajax()` *asynchronous* as its name implies? – David Feb 15 '17 at 12:33
  • yes actually it's ajax() function. – Lamar Feb 15 '17 at 12:38
  • 1
    You best read: [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). You have a problem already with `getfromajax()` – charlietfl Feb 15 '17 at 12:38
  • It's not about returning the response, but rather passing it to the call back function. please read the question thoroughly. – Lamar Feb 15 '17 at 12:40
  • But there is no way that `val` is a value returned by ajax because ajax is asynchronous. Show code for `getfromajax` – charlietfl Feb 15 '17 at 12:41
  • consider it another function, which i'm capable to retrieve value from asynchronous ajax call ;) – Lamar Feb 15 '17 at 12:46
  • Unless you return a promise what you are saying can't be done. You could however pass your callback into `getfromajax` and call it there – charlietfl Feb 15 '17 at 12:47

1 Answers1

0

You'd just pass it to the callback function as an argument

function getValue(callback){
    var val = getfromajax();

    callback(val);
}

var myval = getValue(function(myvalue){
    alert(myvalue)
});

Note that this doesn't work if getfromajax is asynchronous.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • So getValue has to return statement, what does "var myval" actually does? – Lamar Feb 15 '17 at 12:35
  • Actually that does it, thanks! BTW, getfromajax is an alias for $.ajax() call, and I am assigning val in the .done() scope. – Lamar Feb 15 '17 at 12:51