Within my application, there is a function that returns a promise. Inside this function, I wait for an image in the DOM to become available and then extract that element to generate base64 data from it.
getCodesOfOneMerchant(merchantDataEntry: MerchantData) {
var codesOfMerchant = [];
return new Promise(async (resolve, reject) => {
for (let index = 0; index < merchantDataEntry.qrPayloadList.length; index++) {
const value = merchantDataEntry.qrPayloadList[index];
const payLoad = value.qrPayload;
this.qrvalue = payLoad;
while (!document.querySelector(".qrcode img")) {
await new Promise(r => setTimeout(r, 500));
console.log("waiting for qr");
}
console.log("QR element is available");
const qrEle = document.getElementById('qrcode');
let imgBase64Data = this.getBase64Image(qrEle.firstChild.firstChild);
console.log('Base64 = ' + imgBase64Data);
var qrName = merchantDataEntry.serviceName + "-" + value.branch + "-" + value.mobile;
let userQr: UserQr = new UserQr();
userQr.name = qrName;
userQr.qr = imgBase64Data;
codesOfMerchant.push(userQr);
console.log('1')
if (index == merchantDataEntry.qrPayloadList.length - 1) {
resolve();
}
}
console.log('2')
console.log('Returning data = ' + JSON.stringify(codesOfMerchant));
return codesOfMerchant;
});
}
The following function calls the above one:
async downloadQrCodesOfAllSelectedMerchants() {
var qrCodesForAllMerchants = [];
const filteredData = this.merchantDataList.filter(entry => entry.qrSelected);
const promises = filteredData.map(async (value) => {
const qrCodesOfMerchant = await this.getCodesOfOneMerchant(value);
return qrCodesOfMerchant;
});
const qrCodesOfAll = await Promise.all(promises);
console.log('HELLO');
console.log(qrCodesOfAll); // this prints undefined
console.log('DONE')
}
Although I have returned the promise inside the first method, the calling function still receives undefined. I cannot understand what is wrong there.
As you can see, I just log the data to return to the console inside the second function just before returning. The data is there.
Could someone please assist me with this issue? Thank You..!