In my application I have a function that returns a promise. What I do inside that function is, waiting for an image in DOM to be available and extract that element to generate base64 data of 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;
});
}
Following is the function which calls 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')
}
Even though 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. Data is there.
Can someone please help me here. Thank You..!