0

This may sound like a very basic question, but this is the first time I have to deal with something like this. Also, I tried to search, but I don't really know what to type as a search query.

I have this code:

function getGitInfo() {
    var commit;
    git.short(function (str) {
        commit = str;
        console.log("inner Commit Var: " + commit);
    });
    console.log("Outter Commit Var: " + commit);
    return commit;
};

and i'm trying to get str returned by getGitInfo() function.

From the above code, in my console I get only the "inner commit var", with the right value, but I never get the outer one.

How can i return str so that in another variable i can just do:

var test = getGitInfo();

and have returned as test the value from str?

NB: this code uses git-rev node modules (git-rev)

Thanks, and sorry again for the stupid question :)

Nick
  • 13,493
  • 8
  • 51
  • 98
  • 2
    I'm guessing `git.short` is asynchronous, meaning you have to wait for it to execute and _call back_ `function (str)` to get the result. So either use a callback in `getGitInfo` that you call inside `git.short`'s callback or maybe start using promises (though they'll do exactly the same but with a different and maybe better coding style). – Sergiu Paraschiv Feb 22 '16 at 16:24
  • 1
    You can't return values from asynchronous functions. By the time they execute it is too late. – Quentin Feb 22 '16 at 16:24
  • 1
    The API is probably asynchronous, which means that the callback to `git.short()` will be called only when the underlying operation completes. In general, what you're asking here is not possible. Instead, you can design your own API with your own callback, and invoke that in the callback to `git.short()`. – Pointy Feb 22 '16 at 16:25

0 Answers0