node.js - Async await not working in forEach -
i have following code:
async function goodusers(users) { const filteredusers = []; users.foreach(async (userinstance) => { console.log('test1'); const fromusercontacts = await db.usercontactinvite.findall({ where: { fromuserid: userinstance.id, }, }); console.log('test2'); await fromusercontacts.foreach((fromusercontact) => { console.log('test3'); const userjson = fromusercontact.tojson(); userjson.contactstate = 'invitation_sent'; filteredusers.push(userjson); }); console.log('test4'); }); console.log('filtered', filteredusers); return filteredusers; }
when call goodusers following output: test1 filtered test2 test3 test4
filtered should last (obviously).
i tried various options seem not understanding here. guys notice what's going on?
this's correct behavior, async/await
affect function used. need replace foreach
calls callback each element, for
operator:
async function goodusers(users) { const filteredusers = []; for(user in users) { console.log('test1'); const fromusercontacts = await new promise(resolve => settimeout(() => resolve(['c1', 'c2']), 500)); console.log('test2'); fromusercontacts.foreach(fromusercontact => { console.log('test3'); filteredusers.push('json'); }); console.log('test4'); } console.log('filtered', filteredusers); return filteredusers; } goodusers(['u1', 'u2']);
Comments
Post a Comment