I am a new comer to javascript world and I am coming from a Java background. This whole async await thing is completely new to me.
In my current assignment, I have something similar to what I am describing below.
I have two loops which are nested. In the inner loop, I am doing some async stuff. The outer loop iteration must wait until the inner loop complete its task.
This is what I have coded so far.
var bar = ['a', 'b', 'c'];
var foo = [1, 2];
await Promise.all(bar.map(async (barItem, barIndex, barArray) => {
console.log('OUTER VALUE = ' + barItem);
await new Promise((resolve, reject) => {
foo.forEach(async (value, index, array) => {
console.log(value);
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");
if (index === array.length - 1) resolve();
});
}).then(() => {
console.log('All done!');
});
}));
I need console log to be like this.
OUTER VALUE = a
1
waiting for qr
QR element is available
2
waiting for qr
QR element is available
OUTER VALUE = b
1
waiting for qr
QR element is available
2
waiting for qr
QR element is available
..
..
..
But what it prints is,
OUTER VALUE = a
1
2
OUTER VALUE = b
1
2
..
..
waiting for qr
QR element is available
waiting for qr
QR element is available
..
..
Can I know how should I do this to get the desired output? Why doesn't the outer loop wait even if await is there? Thank You..!