0

I'm using the npm module ajax-request, and I'm having trouble storing the data. I have a feeling I'm just not grasping callbacks properly, but have followed examples, yet still to no avail. Any help would be greatly appreciated.

var productData = 'test';
function sendajax() {
    ajax({
        url: url,
        method: 'GET',
    }, (err, res, body) => {
        // Callback function
        returnData(body);
    });
}
function returnData(data) {
    // set variable
    productData = data;
}

alert(productData);
DorianHuxley
  • 642
  • 4
  • 10
  • 22
  • 1
    Possible duplicate of [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) – Adam Azad Jan 20 '17 at 16:37
  • try moving `alert(productData)` right after the assignment `productData = data` and within the function – Brian Jan 20 '17 at 16:41
  • Short answer: that's not how callbacks work. If you move the `alert` into the callback you will see that it does indeed alert the data received back from the server (assuming no error). – Jared Smith Jan 20 '17 at 16:41
  • How then would I return the data retrieved so that I could store it in a variable? Or is this just making it act synchronously? – DorianHuxley Jan 20 '17 at 16:44
  • @DorianHuxley yes, that is exactly the problem, you are treating async as if it were sync. You can either move all of your code that needs to touch that data into the callback (or into functions called inside the callback and passed the data as argument) or use Promises. – Jared Smith Jan 20 '17 at 16:53
  • @JaredSmith That's perfect, I'll look into that. Thanks very much – DorianHuxley Jan 20 '17 at 16:54
  • Naming your function onServerResponse instead of returnData may make your code clearer. – RobertoNovelo Jan 20 '17 at 17:00

0 Answers0