在meteor.js中执行长时间运行的服务器方法

问题描述 投票:0回答:1

我正在开发一个应用程序,其中:

  • 客户端点击按钮触发服务器上长时间运行的任务
  • 服务器执行长时间运行的任务并更新任务进度(假设每分钟 10%)
  • 客户端会在每次服务器进度更新时更新

我能够:

  • 从客户端触发服务器方法
  • 服务器方法执行任务并更新客户端
  • 但是一旦进度达到 100%,我就无法停止执行,并且 ui 会永远更新进度

这是我的服务器方法:

Meteor.methods({
'tasks.Create'() {


if (!this.userId) {
  throw new Meteor.Error('Not authorized.');
}

const id = TasksCollection.insert({
  progressionInPercentage:0,
  createdAt: new Date(),
  userId: this.userId,
});


Meteor.setInterval(()=>{const currentProgressionInPercentage = (ExportsCollection.findOne({_id:id})).progressionInPercentage
   ExportsCollection.update({_id:id},{$set:{progressionInPercentage:currentProgressionInPercentage + 5}})},1000)

   // can I use the clearInterval
  },
javascript asynchronous meteor meteor-blaze
1个回答
0
投票

Meteor 还提供了一种清除间隔的方法,通过

Meteor.clearInterval
:

Meteor.methods({
  'tasks.Create' () {

    if (!this.userId) {
      throw new Meteor.Error('Not authorized.');
    }

    const id = TasksCollection.insert({
      progressionInPercentage: 0,
      createdAt: new Date(),
      userId: this.userId,
    });

    const intervalId = Meteor.setInterval(() => {
      const currentProgressionInPercentage = (ExportsCollection.findOne({ _id: id })).progressionInPercentage
      
      if (currentProgressionInPercentage >= 100) {
        return Meteor.clearInterval(intervalId)
      }
      
      ExportsCollection.update({ _id: id }, { $set: { progressionInPercentage: currentProgressionInPercentage + 5 } })
    }, 1000)
  }
})

一旦百分比等于或大于 100 在间隔处理函数内,只需清除间隔即可。

资源:

© www.soinside.com 2019 - 2024. All rights reserved.