0

I'm new in javascript and struggling in asynchronous concept of javascript. In the following code the function handler.flexCarouselReply, which should wait for the resultArr, is executed before promise is finished.

new Promise((resolve) => {
    const resultArr = checkRedeemList.map((redeemPath) => {
      const couponCode = redeemPath.id;
      redeemPath.get().then((redeemInfo) => {
        if (redeemInfo) {
          console.log(`checking ${couponCode}`);
          const redeemData = redeemInfo.data();
          const createDate = redeemData.CreatedDate;
          const expireDate = redeemData.ExpiredDate;
          console.log(`${couponCode} createDate ${createDate} expireDate ${expireDate}`);
          const isUsed = redeemData.UsedDate;
          if (!isUsed) {
            console.log(`${couponCode} is active`);
            const reward = redeemData.Reward;
            reward.get().then((rewardInfo) => {
              const rewardData = rewardInfo.data();
              const title = rewardData.Title;
              const backgroundColor = rewardData.ButtonColor;
              const imgUrl = rewardData.TransparentImageUrl;
              return {
                "type": "bubble",
                "direction": "ltr",
                "header": {
                  "type": "box",
                  "layout": "vertical",
                  "contents": [{
                      "type": "box",
                      "layout": "baseline",
                      "contents": [{
                          "type": "text",
                          "text": "รหัสรางวัล:",
                          "flex": 2,
                          "contents": [],
                        },
                        {
                          "type": "text",
                          "text": `${couponCode}`,
                          "flex": 4,
                          "contents": [],
                        },
                      ],
                    },
                    {
                      "type": "box",
                      "layout": "baseline",
                      "contents": [{
                          "type": "text",
                          "text": "สถานะ:",
                          "flex": 2,
                          "contents": [],
                        },
                        {
                          "type": "text",
                          "text": "ใช้งานได้",
                          "weight": "bold",
                          "color": "#4FEA0BFF",
                          "flex": 4,
                          "contents": [],
                        },
                      ],
                    },
                  ],
                },
                "hero": {
                  "type": "image",
                  "url": `${imgUrl}`,
                  "size": "full",
                  "aspectRatio": "1.51:1",
                  "aspectMode": "fit",
                  "backgroundColor": `${backgroundColor}`,
                },
                "body": {
                  "type": "box",
                  "layout": "vertical",
                  "contents": [{
                      "type": "box",
                      "layout": "baseline",
                      "contents": [{
                          "type": "text",
                          "text": "ชื่อรางวัล:",
                          "flex": 2,
                          "contents": [],
                        },
                        {
                          "type": "text",
                          "text": `${title}`,
                          "size": "xs",
                          "flex": 4,
                          "wrap": true,
                          "contents": [],
                        },
                      ],
                    },
                    {
                      "type": "box",
                      "layout": "baseline",
                      "contents": [{
                          "type": "text",
                          "text": "วันที่แลก:",
                          "flex": 2,
                          "contents": [],
                        },
                        {
                          "type": "text",
                          "text": `${createDate}`,
                          "size": "xs",
                          "flex": 4,
                          "wrap": true,
                          "contents": [],
                        },
                      ],
                    },
                    {
                      "type": "box",
                      "layout": "baseline",
                      "contents": [{
                          "type": "text",
                          "text": "วันหมดอายุ:",
                          "flex": 2,
                          "contents": [],
                        },
                        {
                          "type": "text",
                          "text": `${expireDate}`,
                          "size": "xs",
                          "flex": 4,
                          "wrap": true,
                          "contents": [],
                        },
                      ],
                    },
                  ],
                },
              };
            });
          } else {
            // not show
            util.log("test", `the ${couponCode} is expired or already used`);
          }
        } else {
          //  redeem in fo already been deleted
          util.log("test", `the ${couponCode} already been deleted`);
        }
      }).catch((error) => {
        //  error get redeem info
        util.log("test", `Error getting redeem information ${error}`);
      });
    });
    resolve(resultArr);
  }).then((resultArr) => {
      console.log(`resultArr ${resultArr}`);
      handler.flexCarouselReply(req, res, replyToken, CONST.ChannelEnum.BOT, resultArr);
  };

How can I manage to ordered the step of this execution.

  • 1
    you `resolve(resultArr);` before the asynchronous code inside `checkRedeemList.map((redeemPath) => {` has a chance to execute – Bravo Aug 15 '21 at 09:58
  • You're calling `resolve(resultArr)` without waiting for the promises in it to settle. To wait for a bunch of promises to settle, you can use `Promise.all` (or `Promise.allSettled` depending on your use case). See the [linked question's answers](https://stackoverflow.com/questions/31426740/) for details. But also, when you already have a promise/promises (which you do from `redeemPath.get()`), [there's no need for `new Promise`](https://stackoverflow.com/questions/23803743/); use the promise/promises you have. Here's an example: https://pastebin.com/Su7nBTZV – T.J. Crowder Aug 15 '21 at 10:11

0 Answers0