How to wait for async actions inside AWS Lambda?

Sometimes, we want to wait for async actions inside AWS Lambda.

In this article, we’ll look at how to wait for async actions inside AWS Lambda.

How to wait for async actions inside AWS Lambda?

To wait for async actions inside AWS Lambda, we can return a promise from method that does async actions.

Then we can use await to wait for the action to complete.

For instance, we write

exports.handler = async (event) => {
  const uploadPromises = folder.files.map(file => {
    return s3.putObject({
      Bucket: "mybucket",
      Key: file.name,
      Body: file.data
    }).promise();
  });

  await Promise.all(uploadPromises);
  return 'exiting'
};

to call folder.files.map with a callback to return the promise returned by promise after calling putObject.

Then we call Promise.all with uploadPromises to run all the promises in parallel and wait for all of them to be done with await before running the return statement.

Conclusion

To wait for async actions inside AWS Lambda, we can return a promise from method that does async actions.

Then we can use await to wait for the action to complete.