0

I have the code as below, which prints the largest partyCode:

Working:

var partyWithLargestPartyCode = Party.find().sort("-partyCode").limit(1); 
var largestPartyCode;
partyWithLargestPartyCode.exec(function(err, p) {
    largestPartyCode = p[0].partyCode;
    console.log(largestPartyCode);    
});

Output:

3

Not Working:

var partyWithLargestPartyCode = Party.find().sort("-partyCode").limit(1); 
var largestPartyCode;
partyWithLargestPartyCode.exec(function(err, p) {
    largestPartyCode = p[0].partyCode;
});

console.log(largestPartyCode);    

output:

undefined

So, I would like to make the second code block to work. How can I do that??

Vishal
  • 6,238
  • 10
  • 82
  • 158
  • 4
    Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – James Thorpe Aug 12 '16 at 08:18
  • You cannot output `largePartyCode` before it is being found / calculated. – Yeldar Kurmangaliyev Aug 12 '16 at 08:19
  • @YeldarKurmangaliyev I know that, So, I want to make the function syncronous. – Vishal Aug 12 '16 at 08:20
  • @Vishal `exec` is an asynchronous method, you cannot call it synchronously. It is a common practice for JavaScript and Node.JS. Why would you want to call it synchronously? – Yeldar Kurmangaliyev Aug 12 '16 at 08:22
  • Because I want to save a new party and I want its partyCode to be automatically calculated based on the largest partyCode. – Vishal Aug 12 '16 at 08:24
  • See: http://stackoverflow.com/questions/17460556/undefined-return-value-from-the-function-call-javascritpt/17460802#17460802 – slebetman Aug 12 '16 at 09:15

1 Answers1

1

You can't make the second example work, because this is how asynchrony works. It takes some time for partyWithLargestPartyCode.exec() to process and will always execute later than console.log(largestPartyCode);.

If you want to learn more about it, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

In the future you will be able to write asynchronous code in a synchronous manner with async/await that will look something like this:

async function myFunc() {
    var myVar = await asynchFunction();
    console.log(myVar); // this will work
}