Promise.all(promiseList) is not working but Promise.all(promiseList[0]) is

Viewed 217

I am using aws lambda that gets a list of items and it pushes items in the table asynchronously. Here promise.all(promiseList) does not add the data in the table but doing promise.all(promiseList[0]) ensures that my first element is pushed in the table. How can I make it to wait for all? My code-

let promiseList = [];
    // await Promise.all(
    promiseList.push(
        event.Records.map(async record => {
                console.log(record.dynamodb.Keys.ServiceOrderId.S);
                console.log('Inside initiate payment');
        
                const paymentObject = {
                    paymentId: record.dynamodb.Keys.ServiceOrderId.S,
                    totalAmount: "1200"
                };
                console.log(paymentObject);
                
                const dynamoDBParams = {
                    TableName : TABLE_NAME,
                    Item : paymentObject
                };
                return await  DynamoDBClient.put(dynamoDBParams).promise();
            }
        )
    );
    return await  Promise.all(promiseList[0]);
1 Answers

couple of changes I can see

  • We don't need to await for every put to complete, it will be inefficient, we want continue executing all at once.
  • DynamoDBClient.put(dynamoDBParams).promise() is returning a promise, which can be pushed into an array, rather than pushing entire loop

Here is how full Lambda looks like:

const AWS = require("aws-sdk");
AWS.config.update({ region: "us-east-1" });
let docClient = new AWS.DynamoDB.DocumentClient();

exports.handler = async function(event) {
  const table = 'test'
  
  var promiseArray = [];
  event.Records.map(record => {
    console.log('record', record);
      const promise = docClient.put({
        TableName: table,
        Item: {
          pk: record.pk,
          title: record.title,
        },
      }).promise();
      promiseArray.push(promise)
  })
  return Promise.all(promiseArray);
}
Related