How To Use Promise With Nested Foreach
I am finding all users wallets in nested foreach loop but i am unable to figure out where to use resolve() for return callback, function genwallets() { return new Promise((res
Solution 1:
forEach
doesn't work with promises. either use for...of
or Promise.all
something like this
functiongenwallets() {
returnnewPromise((resolve, reject) => {
var i = 0;
try {
db.users.findAll({}).then(users => {
db.supportedTokens.findAll({}).then(tokens => {
for(const user of users) {
for(const token of tokens) {
db.wallets
.findOne({
where: { userId: user["id"], supportedTokenId: token["id"] }
})
.then(wallet => {
console.log(JSON.stringify(wallet));
});
}
}
});
});
} catch (err) {
console.log(err);
}
});
}
by the way you dont need to wrap it in promise.
You could simplify this using async/await
async function genwallets() {
const users = await db.users.findAll({});
const tokens = await db.supportedTokens.findAll({});
for(const user of users) {
for(const token of tokens) {
const wallet = await db.wallets
.findOne({
where: { userId: user["id"], supportedTokenId: token["id"] }
});
}
}
}
Post a Comment for "How To Use Promise With Nested Foreach"