使用异步/等待在议程中运行作业

时间:2018-11-26 11:20:02

标签: javascript node.js mongoose agenda

我有一些单独的模块和模型。现在,我想添加agenda以在计划模式下运行作业。当我在sync中编写代码时,一切工作正常,但我想使用asyncawait处理它。 这是我的代码:

从“模型”导入{用户};

module.exports = async function (agenda) {
    agenda.define('userjob', async (job) => {
        console.log(`running job  for user: ${job.attrs.data.userId}`);
        const user = await User.findOne({ _id: job.attrs.data.userId });
        console.log(user);
    });
};

并在我的anenda索引文件中:

import Agenda from 'agenda';

   const agenda = new Agenda({ db: { address: mongo } });
agenda.on('success', (job) => {
    console.log(`job ${job.attrs.name} was successfull.`);
});

在我的某些路线(仅用于测试)中,我这样称呼:

agenda.now('userjob', { name: 'name job', userId: '5bf993f11ad57c4dd9edcd74' });

这里的问题是我登录user对象时

const agenda = new Agenda({ db: { address: mongo } });

agenda.on('ready', () => {
    console.log('agenda is ready.');
});

agenda.on('start', async (job) => {
    console.log(`job ${job.attrs.name} is started.`);
});

agenda.on('complete', (job) => {
    console.log(`job ${job.attrs.name} is finished.`);
});

agenda.on('success', (job) => {
    console.log(`job ${job.attrs.name} was successfull.`);
});

agenda.on('error', (job) => {
    console.log(`job ${job.attrs.name} was failed.`);
});

jobTypes.forEach((type) => {
    require(`./jobs/${type}`)(agenda);
});



(async function () {
    if (jobTypes.length) {
        await agenda.start();
    }
}());


async function graceful() {
    await agenda.stop();
    process.exit(0);
}

process.on('SIGTERM', graceful);
process.on('SIGINT', graceful);

module.exports = agenda;

我认为输出顺序错误:

job saveInvestore is started.
running job  for user: 5bf993f11ad57c4dd9edcd74
job saveInvestore was successfull.
job saveInvestore is finished.
{ investmentInfo:
   { fundCode: [],
     FirstName: 'test',
     LastName: 'testian',
     Email: 'test@test.test',
     Mobile: '0912121212',
     MelliNumber: '1234554321' },
  role: 'BASIC',
  status: 'ACTIVE',
  meta: '{}',
  fundCode: [],
  _id:
   ObjectID {
     _bsontype: 'ObjectID',
     id: <Buffer 5b f9 93 f1 1a d5 7c 4d d9 ed cd 74> },
  firstName: 'test',
  lastName: 'testian',
  email: 'test@test.test',
  nationalCode: '1234554321',
  phoneNumber: '0912121212',
  gender: 'MALE',
  createdAt: 2018-11-24T18:09:53.912Z,
  updatedAt: 2018-11-24T18:09:53.912Z,
  __v: 0 }

我如何才能使议程按预期async/await工作的确切顺序进行工作?

1 个答案:

答案 0 :(得分:0)

议程将第二个参数done注入到作业处理程序中,这是您在作业结束时应调用的回调。

module.exports = async function (agenda) {
    agenda.define('userjob', async (job, done) => {
        console.log(`running job  for user: ${job.attrs.data.userId}`);
        const user = await User.findOne({ _id: job.attrs.data.userId });
        console.log(user);
        // Now your async/await job works!
        return done();
    });
};