如何使function同步

我有下面的代码,它打印最大的partyCode:

加工:

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

输出:

 3 

不工作:

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

输出:

 undefined 

所以,我想使第二个代码块工作。 我怎样才能做到这一点??

你不能使第二个例子工作,因为这是asynchronous工作。 partyWithLargestPartyCode.exec()需要一些时间来处理,并且总是比console.log(largestPartyCode); partyWithLargestPartyCode.exec()执行时间要partyWithLargestPartyCode.exec() console.log(largestPartyCode);

如果您想了解更多信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

在将来,您将能够以async/await方式以async/await方式编写asynchronous代码,如下所示:

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