async function myfunc(fruits) {
for (i = 0; i < 5; i ) {
fruits.forEach(fruitId => {
colors = await dbHelper.getColor(fruitId);
colors.forEach(color => {
taste = await dbHelper.gettaste(color);
});
});
}
}
How do we get this to work,with multiple for loops.The dbhelper functions are fetching some data from the database.
CodePudding user response:
Your code have a several mistakes (check out below) and should look like this:
async function myfunc(fruits) {
try {
for (let i = 0; i < 5; i ) {
for (let fruitId of fruits) {
colors = await dbHelper.getColor(fruitId);
for (let color of colors) {
taste = await dbHelper.gettaste(color);
}
}
}
} catch(err) {
// Handle somehow
}
}
Why?
- You call async methods from
dbHelper
inside offorEach
arrow function instead ofmyfunc
directly, soawait
keyword will not allowed there, you should addasync
keyword to methods where async methods calls. - Awaiting will not works there because
forEach
loop can't pause code execution. Solution: changeforEach
loops tofor (... in/of ...)
. - You didn't handle errors anywhere. Keep in mind that any async method can be rejected, so you need to be ready for it and handle errors somehow. Solution: add
try/catch
.
Also you can check this question about asyncing during loop.
CodePudding user response:
Assuming that you want to retrieve an array of taste you can do something like this
async function myfunc(fruits) {
const colors = await Promise.all(fruits.map(fruitId =>dbHelper.getColor(fruitId)));
const tastes = await Promise.all(colors.map(color => dbHelper.gettaste(color)));
...
}
or shorter
async function myfunc(fruits) {
const colors = await Promise.all(fruits.map(dbHelper.getColor));
const tastes = await Promise.all(colors.map(dbHelper.gettaste));
...
}
CodePudding user response:
Inside forEach you define a new (arrow) function. So it will work if you use like this:
colors.forEach(async (color) => {
taste = await dbHelper.gettaste(color);
});
Your entire code should be:
async function myfunc(fruits) {
for (i = 0; i < 5; i ) {
fruits.forEach(async (fruitId) => {
colors = await dbHelper.getColor(fruitId);
colors.forEach(async (color) => {
taste = await dbHelper.gettaste(color);
});
});
}
}