Gayan Hewa
Gayan Hewa

Reputation: 2397

async await performance hits

For an express Controller method as below, being nested with a few async awaits, will it have any performance hits?

All the logic currently sits in the controller method for simplicity sake. But I am well aware that I can refactor these out.

I have used async on some of the promise resolutions then. And at the top level. I am not sure if this will significantly degrade performance or if its an arguable practice?

  async registerUser(req, res, next) {
    const trx = await transaction.start(this.User.knex());
    let userData = {};
    AuthService.hashPassword(req.body.password)
      .then(password => {
        userData = {
          first_name: req.body.firstName,
          last_name: req.body.lastName,
          email: req.body.email,
          password: password,
          tenant_id: req.body.tenantId
        };

        return userData;
      }).then(async userData => {
        return this.User
          .query()
          .insert(userData);
      })
      .then(async user =>  {
        let token = await AuthService.signPayload(user);
        return {
          token,
          user
        };
      })
      .then(async payload => {
        await trx.commit();
        console.log(payload);
        res.status(201);
        res.jsonp({
          success: true,
          data: {
            user: payload.user,
            token: payload.token
          }
        });
      }).catch(async e => {
        await trx.rollback();
        console.log(e);
        res.status(400);
        res.jsonp({
          success: false,
          errors: true,
          data: {
            message: 'Registration failed',
            user: userData
          }
        })
      });
  }

Upvotes: 0

Views: 408

Answers (1)

Grynets
Grynets

Reputation: 2525

I've changed your code to look more synchronic, so you can see all pros and cons.
About performance hits, it is best solution to use async/await in your code.

About this:

can refactor these out.

const registerUser = (req, res, next) => {
  const trx = await transaction.start(this.User.knex());
  let password;

  try {
    password = await AuthService.hashPassword(req.body.password);
  } catch (e) {
    // Some error. You can throw it or message user or do whatever you want.
    console.error("Error with auth", e.message);
    return await errorTransaction(res, trx);
  }

  let userData = {
    first_name: req.body.firstName,
    last_name: req.body.lastName,
    email: req.body.email,
    password: password,
    tenant_id: req.body.tenantId
  };

  try {
    await this.User.query().insert(userData);
  } catch (e) {
    console.error("Error during insert", e.message);
    return;
  }

  let token = await AuthService.signPayload(user);
  let tokenUserData = {
    token,
    user
  };

  try {
    await trx.commit();
  } catch (e) {
    console.error("Error in commit.", e.message);
    return await errorTransaction(res, trx, userData);
  }
  res.status(201);
  res.jsonp({
    success: true,
    data: {
      user: payload.user,
      token: payload.token
    }
  });
}

const errorTransaction = async (res, trx, userData={}) => {
  await trx.rollback();

  res.status(400);
  res.jsonp({
   success: false,
   errors: true,
   data: {
     message: 'Registration failed',
     user: userData
   }
  });
}

Upvotes: 2

Related Questions