async 내의 map에서 await 못 쓰는 문제

codeing999·2022년 8월 25일
0

JavaScript

목록 보기
13/24

정확히는 async 내의 가장 최상단 바디가 아닌 곳에서 await를 쓸 수없다는 에러가 뜬다.
for문 같은 거는 되지만 map같은 메소드 안에서는 못 쓴다.
이걸 쓸 수 있게 하는 방법이 찾아보니 있었다.

getLikePeople = async (userId) => {
    try {
      const people = await LikeAndDislike.findAll({
        where: { userId, isLike: true },
        attributes: [],
        include: [
          {
            model: User,
            as: "objectUser",
          },
        ],
        raw: true,
      });

      const result = await Promise.all(
        people.map(async (v) => {
          const likeMe = await this.getIsLikeMe(userId, v["objectUser.userId"]);
          return {
            userId: v["objectUser.userId"],
            email: v["objectUser.email"],
            nickname: v["objectUser.nickname"],
            age: v["objectUser.age"],
            address: v["objectUser.address"],
            gender: v["objectUser.gender"],
            imageUrl: v["objectUser.imageUrl"],
            interest: v["objectUser.interest"].split(""),
            x: v["objectUser.x"],
            y: v["objectUser.y"],
            likeMe: likeMe.isLikeMe,
          };
        })
      );

      return result;
    } catch (err) {
      console.error(err);
      return err.message;
    }
  };

이와 같이 async 함수내에서
저 result 부분에서 map 안에서 await를 쓰고 싶은건데,
await Promise.all()로 map메소드 쓰는 곳 전체를 감싸고
map 안에도 async 써주면
그 안에서 await를 쓸 수 있게 된다.

profile
코딩 공부 ing..

0개의 댓글