Async await in for loop

Viewed 50

I have this function and I'm trying to push objects into the "groupData" array and then return the response object but when the function successfully runs, I get "response" as a null object. What is wrong with my code can anyone help? How can I make the function to wait for the map function to finish and then return.

const groupList = async (io, socket, userid) => {
  var response = {};
  try {
    var groupData = [];
    ddb.get({
        TableName: "Tablename",
        Key: { Username: userid },
      })
      .promise()
      .then(async (user) => {
        if (Object.keys(user).length === 0) {
        } else {
          const groups = user.Item.Chatgroups;
          groups.map((g) => {
              ddb.get({
                  TableName: "Tablename",
                  Key: { ChatID: g },
                })
                .promise()
                .then(async (data) => {
                  groupData.push({
                    ChatID: g,
                    Chatname: data.Item.Chatname,
                    Group: data.Item.Group
                  });
                })
                .catch((err) => {
                  console.log("Chat group not found");
                });
            })
            response["groups"] = groupData;
        }
      })
      .catch((err) => {
        response["code"] = 400;
        response["message"] = "Something Went Wrong";
      });
  } catch (error) {
    console.log(error);
  } finally {
    return response;
  }
};
2 Answers

I searched too long for this

for await (item of items) {}

Use Promise.all and if you use async then make use of await.

Here is how your code could look. I removed the error handling -- first test this and when it works, start adding back some error handling (with try/catch):

const groupList = async (io, socket, Username) => {
    const user = await ddb.get({
        TableName: "Tablename",
        Key: { Username },
    }).promise();
    if (!Object.keys(user).length) return {};
    return {
        groups: await Promise.all(user.Item.Chatgroups.map(async ChatID => {
            const { Item: { Chatname, Group } } = await ddb.get({
                TableName: "Tablename",
                Key: { ChatID },
            }).promise();
            return { ChatID, Chatname, Group };
        }))
    };
};
Related