0

I'm using a library called sqs-consumer to process SQS messages. The library is expecting the message handler to look like:

handleMessage: (message, done) => {
    // do some work with `message`
    done();
}

On the other hand though I have async code

async function sendEmail() {
    return await ...
}

Is there a good way to run the sendEmail within handleMessage, wait for it to finish, and then to call done?

petabyte
  • 1,487
  • 4
  • 15
  • 31
  • Possible duplicate of [async/await implicitly returns promise?](https://stackoverflow.com/questions/35302431/async-await-implicitly-returns-promise) – lucascaro Nov 15 '18 at 23:35
  • 2
    Note that `return await` is pretty pointless if that's the only `await` you're using in the function - just use a standard function instead, and you can simply `return` the plain `Promise` – CertainPerformance Nov 15 '18 at 23:36

2 Answers2

1

You can use your promise-based code inside a callback like this:

handleMessage: (message, done) => {
    // do some work with `message`
    sendEmail().then(done).catch(...);
}

In some cases, you could also make a new method for handleMessage() that actually expects a promise to be returned and works with that promise directly rather than using a plain callback at all.


Also, not that there is no point to using return await ... at the end of your function. You can just return the promise directly:

So, instead of:

async function sendEmail() {
    // other code here
    return await someFuncThatReturnsPromise();
}

You can just do:

async function sendEmail() {
    // other code here
    return someFuncThatReturnsPromise();
}

That extra await adds no value or utility.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

As long as the library doesn't care what you return from handleMessage you can also use async/await in the handlerMessage function directly:

handleMessage: async (message, done) => {
    await sendEmail();
    done();
}
Paul
  • 139,544
  • 27
  • 275
  • 264