Vishal Vishal - 3 months ago 6
Node.js Question

How to make the function syncronous

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??

Answer

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
}