Home > Net >  Fastify: How to wait for Redis pub/sub message before sending response?
Fastify: How to wait for Redis pub/sub message before sending response?

Time:12-02

I have a route that needs to wait for a Redis pub/sub message before it can send a response.

  app.post('/route', async function (req: any, rep) {
    // Listen for redis
    redis.on('message', async (ch, msg) => {
      let match = JSON.parse(msg)
      if (match.id == req.body.id) {
        rep.send('ok')
      }
    })
    // How to "wait" here?
  })

As ioredis.on() doesn't return a Promise, I can't use await to block. What can I do to to make the code "wait" for the Redis message?

CodePudding user response:

A simple wrapper should work

app.post("/route", async function (req: any, rep) {
  const [ch, msg] = await waitForMessage(redis);
  let match = JSON.parse(msg);
  if (match.id == req.body.id) {
    rep.send("ok");
  }
});

function waitForMessage(redis) {
  return new Promise((resolve) =>
    redis.on("message", (...args) => resolve(args))
  );
}

CodePudding user response:

Made a modification to Konrad's answer so that you can handle multiple messages until some condition matches.

export async function onMessage(redis: ioredis, exec: (...args: any[]) => boolean) {
  return new Promise((resolve) => {
    redis.on('message', (...args) => { if (exec(args)) resolve(args) })
  })
}
  • Related