2

I have a Lambda function in AWS using Node 8.1 which initiate MSSQL request ( to an external server , which is not in aws)

When I'm using the non async handler with non async code (but callbacks )—

exports.handler = (event, context, callback) => {...}

— Everything is OK.

Proof: For this code, which uses callbacks-

exports.handler = (event, context, callback) => {
     sql.connect(config, err => {
        if (err) {
          callback(err);
        } else {
          const req = new sql.Request();
          req.query(
            'select * from img.dbo.images where imageid = 1641',
            (error, result) => {
              if (error) {
                callback(error);
              } else {
                sql.close();
                callback(null, result.recordset);
              }
            }
          );
        }
      });
};

I get this response :

enter image description here

However , If I change the code to the async version :

exports.handler = async (event, context, callback) => {
  try {
    let pool = await sql.connect(config);
    let result1 = await pool
      .request()
      .query('select * from img.dbo.images where imageid = 1641');

    callback(null, result1.recordset);
  } catch (err) {
    callback(err);
  }
};

— I get a Timeout error(sure it's related to a non-fulfill promise) :

enter image description here

Question

Why doesn't the async version work ? how can I make it work?

1 Answer 1

4

Remove the callback param and just return the result instead. Also, you can avoid catching errors unless you need to do any special handling

exports.handler = async (event, context) => {
  const pool = await sql.connect(config);
  return await pool
    .request()
    .query('select * from img.dbo.images where imageid = 1641');
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. working. One question though , When an error occurs , should I return it ? or should I callback(error) it ? can you please provide a small example in this ^ code ?
@RoyiNamir forget callback() with async / await, if you want to catch the error then you should return it.
thanks for this, i never came across anything offical to return request/response instead of using callback so was stuck as well

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.