petabyte
petabyte

Reputation: 1567

Using async function within synchronous code

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?

Upvotes: 0

Views: 2167

Answers (2)

Paul
Paul

Reputation: 141829

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

Upvotes: 1

jfriend00
jfriend00

Reputation: 707148

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.

Upvotes: 1

Related Questions