meteor.js – 如何检查asynchronouscallback的值

CONTEXT

我做了一个调用,如果成功,将布尔值从false更改为true。 然后,在这个调用之外,我检查这个布尔值是否为真,如果是的话,我路由到另一个页面。

问题

控制台日志指出,在调用有时间改变布尔值之前,正在执行检查布尔值的if语句。 我意识到这是由于asynchronous性,但不知道这是什么正确的devise模式。 这是一个片段:

//set variables to check if the even and user get updated or if error var eventUpdated = false; Meteor.call('updateEvent', eventId, eventParams, function(error, result){ if(error){ toastr.error(error.reason) } else { var venueId = result; toastr.success('Event Info Updated'); eventUpdated = true; console.log(eventUpdated) } }); console.log(eventUpdated) if (eventUpdated) { Router.go('/get-started/confirmation'); } 

可能的解决scheme

我猜我需要一种方法来保持执行的语句,直到callback返回一个值。 基于谷歌search,我认为这与这个有关,但不太清楚如何实际使用它。

由于条件是在callback函数返回一个值之前运行的,因此您需要一个条件reflection式地运行的函数。 我使用了下面的代码:

  Tracker.autorun(function(){ if (Session.get('userUpdated') && Session.get('passwordUpdated') && Session.get('eventUpdated')) { Router.go('/get-started/confirmation'); } }); 

你可以在这里阅读更多关于meteor的反应。

不。 问题是,因为它是一个asynchronous函数,所以:

 console.log(eventUpdated) if (eventUpdated) { Router.go('/get-started/confirmation'); } 

在实际呼叫之前运行。 在调用中使用Session.set,如下所示:

 Session.set("eventUpdated", "true"); 

然后在外面:

 eventUpdated = Session.get("eventUpdated"); console.log(eventUpdated) if (eventUpdated) { Router.go('/get-started/confirmation'); } 

由于会话是一个无功variables,您应该正确地获取当前值。