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?

2
  • Possible duplicate of async/await implicitly returns promise? Commented Nov 15, 2018 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 Commented Nov 15, 2018 at 23:36

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.