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.