Reputation: 416
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((resolve, reject) => {
var i = 0;
try {
db.users.findAll({}).then((users)=>{
db.supportedTokens.findAll({}).then((tokens)=>{
users.forEach(function(user) {
tokens.forEach(function(token) {
db.wallets.findOne({where:{userId: user['id'], supportedTokenId: token['id']}}).then((wallet)=>{
console.log(JSON.stringify(wallet));
})
});
});
})
});
} catch (err) {
console.log(err);
}
});
}
Upvotes: 0
Views: 554
Reputation: 7770
forEach
doesn't work with promises. either use for...of
or Promise.all
something like this
function genwallets() {
return new Promise((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"] }
});
}
}
}
Upvotes: 1