I want to run the code asynchronously

Asked 2 years ago, Updated 2 years ago, 42 views

Hi, how are you?

I want to find data in the database and put it in json form.

Json's response is executed before data is found and contained, so where should I use wait to find data and then respond?

It's too difficult because of the map function in the middle

Originally, I used it right away without making it as a function, but I made it separately because I heard that wait is used in front of the function. Help me.

After the response, the data is found well. How do I transform it?

// Lookup for posts
router.get("/", async (req, res) => {
  const datas = await Post.findAll(
    { { order: [["createdAt", "DESC"]] }
  );

  function findLike() {
    datas.map(async (e) => {
      const likeCount = await Like.findAll({ where: { postId: e.postId } });
      e.likes = likeCount.length;
    });
  }

  function response() {
    res.json({
      data: datas.map((e) => {
        return {
          postId: e.postId,
          userId: e.userId,
          nickname: e.nickname,
          title: e.title,
          createdAt: e.createdAt,
          updatedAt: e.updatedAt,
          likes: e.likes,
        };
      }),
    });
  }

  await findLike();
  await response();
});

node.js

2022-09-20 08:40

1 Answers

// Look up posts
router.get("/", async (req, res) => {
    const datas = await Post.findAll(
      { { order: [["createdAt", "DESC"]] }
    );

    datas.map(async (e) => {
        const likeCount = await Like.findAll({ where: { postId: e.postId } });
        e.likes = likeCount.length;

        res.json({
            data: datas.map((e) => {
              return {
                postId: e.postId,
                userId: e.userId,
                nickname: e.nickname,
                title: e.title,
                createdAt: e.createdAt,
                updatedAt: e.updatedAt,
                likes: e.likes,
              }
            })
        });
    });

});


2022-09-20 08:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.