我想使用带有Node.js的议程来安排一个简单的任务,但是当它包裹在apiRoutes(快速路由器)中时,它没有执行

var apiRoutes = express.Router();
app.use('/api', apiRoutes);

apiRoutes.post('/scheduler/submit', function (req, res) {
    agenda.define('test', function () {
         console.log('Test');
    });

    agenda.on('ready', function () {
         agenda.every('*/1 * * * *', 'test');
         agenda.start();
    });
});


但是,如果我将代码放在外面,则可以。嗯,有什么主意吗?

var apiRoutes = express.Router();
app.use('/api', apiRoutes);

agenda.define('test', function () {
      console.log('Test');
});

agenda.on('ready', function () {
      agenda.every('*/1 * * * *', 'test');
      agenda.start();
});

apiRoutes.post('/scheduler/submit', function (req, res) {
    // Leave blank
});

最佳答案

问题是on函数。当您在快速代码中调用agenda.on('ready', ...)时,您将添加对agenda发射器的ready数组的侦听,但是该信号仅在服务器初始化时agenda连接到数据库时出现。换句话说,在服务器启动时agenda连接到数据库之后,它将不再发出相同的信号,这就是为什么express API中的代码未执行的原因。

要解决此问题,建议您确认agenda已成功连接到数据库并运行该过程。如果不是,则添加.on('ready', ...)事件侦听器。

样本来源:

var apiRoutes = express.Router();
app.use('/api', apiRoutes);

// Use this to determine if a conneciton has been established between agenda
// and the database
var connectionEstablised = false;

// When the connection is established, set the flag
agenda.on('ready', function() {
    connectionEstablished = true;
});

// It's better practice to have this function defined on your agenda object
// When the server initializes rather than having initializing it only if a POST
// request occurrs.
agenda.define('test', function () {
     console.log('Test');
});



apiRoutes.post('/scheduler/submit', function (req, res) {

    // Only execute this code if you can confirm the connection is established
    if (connectionEstablished) {
        agenda.every('*/1 * * * *', 'test');
        agenda.start();
    }
});

关于javascript - 如何在Node.js中的快速apiRoute中包装议程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41228811/

10-12 20:47