Matt
Matt

Reputation: 1432

Converting Express app from promises to async/await

I've been using Promises for a long time and I've always disliked how bulky written code looked. So it makes sense that I love async/await (in theory).

However, you can only use await within an async function. If I currently have each route as a function (ex export function createLike(req, res, next)), can that route be an async function? Is there anything I need to check if I do that? Or do strange things happen if I do that? I could keep the function as a normal function with an async function called within it like so (if that's the case):

export function createLike(req, res, next) {
    doStuff()  // does this need to be "await doStuff()" if it's the only actionable call in the parent function?

    async function doStuff() {
        // do asynchronous stuff via async/await
        res.status(200).send('success')
    }
}

Upvotes: 2

Views: 923

Answers (2)

Josh from Qaribou
Josh from Qaribou

Reputation: 6898

export async function createLike(req, res, next) {

Easy-peasy. Declaring a function as async does little more than make it return a Promise.

Unravelling your whole trivial example:

export async function createLike(req, res, next) {
  // Don't bother putting inside a 'doStuff' if it's all you have.
  // Get straight to the asyncing
  const { something } = await someAsyncMethod();
  const { foo } = await fetch(`/get/this/${something}`).then((r) => r.json());
  console.log(foo);
  res.status(200).send('success')
}

This will wait until it gets someAsyncMethod()s response, then fetches something, before sending the response.

Upvotes: 2

Jason Livesay
Jason Livesay

Reputation: 6377

Use koa 2+. Its built for async/await stuff.

Upvotes: 0

Related Questions