【问题标题】:How to make the function syncronous如何使函数同步
【发布时间】:2016-08-12 08:16:59
【问题描述】:

我有如下代码,打印出最大的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

所以,我想让第二个代码块工作。我该怎么做??

【问题讨论】:

标签: javascript node.js


【解决方案1】:

你不能让第二个例子工作,因为这就是异步的工作方式。 partyWithLargestPartyCode.exec() 需要一些时间来处理,并且总是会晚于 console.log(largestPartyCode); 执行。

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

将来您将能够使用async/await 以同步方式编写异步代码,如下所示:

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

【讨论】:

  • 那我该怎么做呢?
  • 我的意思是有没有其他方法可以在函数执行后获得最大派对代码的值?
  • 只在它的回调内部,就像在第一个例子中一样。
猜你喜欢
  • 1970-01-01
  • 2020-12-20
  • 2017-04-28
  • 2013-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-20
  • 2021-12-04
相关资源
最近更新 更多