方法中的Meteor setTimeout

时间:2016-05-17 16:23:17

标签: javascript mongodb meteor

我有一个名为Games with collection with update updateGame的集合。如果playersCount = 4,我想在客户端上开始游戏,所以我想在4秒后更新字段hasStarted。我尝试了蓝鸟的承诺,但得到了这个错误:"错误:流星代码必须始终在光纤内运行。尝试使用Meteor.bindEnvironment包装传递给非Meteor库的回调。"

export const updateGame = new ValidatedMethod({
  name: 'games.updateGame',
  validate: new SimpleSchema({
    gameId: { type: String },
  }).validator(),
  run({ gameId }) {
    const game = Games.findOne(gameId);
    let playersCount = game.playersCount + 1;
    let isRunning = false;
    if (playersCount === 4) {
      isRunning = true;
      startAfterDelay(gameId, 4000);
    }
    Games.update(gameId, {
      $set: { 
        playersCount,
        isRunning
      },
    });
  },
});

const startAfterDelay = function(gameId, delay) {  
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      Meteor.wrapAsync(
        Games.update(gameId, {
          $set: { 
            hasStarted: true
          },
        })
      );
    }, delay)
  })
}

0 个答案:

没有答案