1

I've seen a lot of posts on here that show how to make an asynchronous function call using callbacks. I've made it work, however, I can't seem to find how to utilize the variable retrieved from the function outside of the function.

        var json = JSON.parse(body);
        var accountID = json.accountId; 
        var getMatchData;

        getRecentMatchData(accountID, function(err, res) {
            getMatchData = res;
            //console.log(res);
        });
        console.log(getMatchData);

I'm trying to use getMatchData to pass into other functions in my app.post but it prints out as undefined. How can I access this variable to use outside of the asynchronous method? Do I use another callback?

  • You put the *console.log(getMatchData)* to the success block of the asynchronous function call, or you put the console.log to a function and execute that function on the success block instead. At least that's what I did when I worked on the js filereader api. And that's what I do on my ajax calls. You'll always get undefined if you try to use a variable that depends on the result of an asynchronous function immediately after calling it – Abana Clara Aug 16 '17 at 07:00
  • the code is asynchronous, you to move `console.log(getMatchData)` into the function handler – Olivier Boissé Aug 16 '17 at 07:01

1 Answers1

1

In this case you will have to use something like async waterfall. In the end it means another callback. Your example code sample is to small to write the right refactoring, but this will help.

async.waterfall([
    function(callback) {
        getRecentMatchData(accountID, function(err, res) {
          callback(err, res); 
          getMatchData = res;
          //console.log(res);
        })
    },
    function(getMatchData, callback) {
        // getMatchData now equals 'res'
        // do what you have to do with getMatchData
        callback(null, 'result');
    }
], function (err, result) {
    // result now equals 'result'
});
Cleriston
  • 750
  • 5
  • 11
  • This looks like I will just end up doing everything in that middle block which is what I could have done in the getRecentMatchData function call anyway. Sounds like there is no real way for me to use the variable outside of the function call. Also the last function is just error checking, right? – Sadaf Chowdhury Aug 16 '17 at 16:27
  • The last function is the callback of your asynchronous waterfall. It also returns the error, if it happens. – Cleriston Aug 16 '17 at 22:54