Home > Enterprise >  Async await in for loop
Async await in for loop

Time:09-14

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;
  }
};

CodePudding user response:

I searched too long for this

  • Related