metro.js-如何从异步回调中检查值



上下文

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

问题

控制台日志表明,在调用有时间更改布尔值之前,正在执行检查布尔值的if语句。我意识到这是因为异步性,但不确定正确的设计模式是什么

     //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');
     }

可能的解决方案

我想我需要一种方法来阻止if语句的执行,直到回调返回一个值。根据谷歌搜索,我认为这与此有关,但不太清楚如何实际使用它。

由于条件是在回调返回值之前运行的,因此您需要一个处于反应运行的函数内部的条件。我使用了以下代码:

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

你可以在这里阅读更多关于流星反应性的信息。

没有。问题是,由于它是一个异步函数,因此:

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');
     }

由于Session是一个反应变量,您应该正确地获得当前值。

最新更新