Bulljs阻止expressAPI请求直到作业完成
创始人
2024-12-26 16:00:37
0

一种方式是使用 async/await 将 Bull 的作业处理程序包装在一个函数中,并使用 Promise 将其返回。然后,在 Express 路由中使用 await 调用此函数,以便在作业完成后继续进行路由处理。以下是一个示例:

const { Queue } = require('bull');

const myQueue = new Queue('myQueue');

async function handleJob(job) {
  console.log(`Starting job ${job.id}`);
  // Do some work here
  console.log(`Job ${job.id} finished!`);
  return true;
}

async function processJob(job) {
  const result = await handleJob(job);
  return Promise.resolve(result);
}

app.post('/jobs', async (req, res) => {
  const { data } = req.body;

  await myQueue.add(data);

  res.json({
    message: 'Job enqueued!'
  });
});

app.get('/jobs', async (req, res) => {
  const jobs = await myQueue.getJobs();

  res.json(jobs);
});

app.get('/jobs/:id', async (req, res) => {
  const { id } = req.params;

  const job = await myQueue.getJob(id);

  res.json(job);
});

app.post('/process-jobs', async (req, res) => {
  const jobs = await myQueue.getJobs();

  for (const job of jobs) {
    await processJob(job);
  }

  res.json({
    message: 'All jobs processed!'
  });
});

在上面的例子中,我们将处理作业的代码封装在 handleJob 函数中,并将其包装在 processJob 函数中,该函数返回一个 Promise。在路由处理函数中,我们使用 await 调用 processJob 函数,以防请求阻塞直到作业完成。

相关内容

热门资讯

透视教学!aa poker辅助... 透视教学!aa poker辅助(透视)透视脚本下载(真是存在有挂);1、用户打开应用后不用登录就可以...
透视辅助!aapoker透视方... 透视辅助!aapoker透视方法(透视)万能辅助器(其实真的有挂)1、aapoker透视方法系统规律...
透视软件!aapoker怎么选... 透视软件!aapoker怎么选牌(透视)透视脚本下载(确实有挂)1、超多福利:超高返利,海量正版游戏...
透视安装!aa poker透视... 透视安装!aa poker透视软件(透视)脚本(好像存在有挂);1、进入游戏-大厅左侧-新手福利-激...
透视透视!aapoker透视怎... 透视透视!aapoker透视怎么用(透视)透视插件(其实存在有挂)aapoker透视怎么用是一种具有...
透视存在!aapoker如何设... 透视存在!aapoker如何设置胜率(透视)透视插件(切实真的是有挂)1、游戏颠覆性的策略玩法,独创...
透视能赢!aapoker辅助工... 透视能赢!aapoker辅助工具安全吗(透视)发牌逻辑(其实是有挂)透视能赢!aapoker辅助工具...
透视挂!aapoker万能辅助... 透视挂!aapoker万能辅助器(透视)辅助(都是有挂);1、用户打开应用后不用登录就可以直接使用,...
透视了解!aapoker辅助怎... 透视了解!aapoker辅助怎么用(透视)插件(竟然是有挂);进入游戏-大厅左侧-新手福利-激活码辅...
透视了解!aapoker怎么提... 透视了解!aapoker怎么提高中牌率(透视)透视脚本入口(其实真的有挂)1、aapoker怎么提高...