0

我有一些分开的模块和模型。现在我想添加agenda以调度模式运行的作业。当我编码sync一切正常但我想用asyncand处理它时await。这是我的代码:

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

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工作?

4

1 回答 1

0

Agendadone在您的作业处理程序中注入了第二个参数,它是您应该在作业结束时调用的回调。

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();
    });
};
于 2019-02-22T20:01:19.147 回答