#Might have an issue with function scope.

67 messages · Page 1 of 1 (latest)

mint forge
#

Hello guys, please check this code. I have tried to explain my doubt in the comments in the code.

import * as mongodb from 'mongodb';
const MongoClient = mongodb.default.MongoClient;
import genSegWallet from './utils/genSegWallet.js';

const uri =
    'MY MONGO CONNECTION LINK';
const client = new MongoClient(uri);

async function getAddrs() {
    const query = await client.db('users').collection('userAddress').find().toArray()
    let balanceList= {}
    query.forEach(async (entry) => {
        const username = await entry['username'];
        const mnemonic = await entry['address']['mnemonic']
        const address = await genSegWallet(mnemonic)
        const addressArr = Object.values(address)
        balanceList[username] = {}
        addressArr.forEach(async (addr, index) => {
            // const bal = await getBal(addr);
            const bal = 0;
            cursor[username][index] = { 'address': addr, 'balance': bal }
        })
      console.log(balanceList) //This prints 3 times cause there are 3 elements in the query array.
    })
    console.log(balanceList) //Does not print
    return cursor;
}

export default getAddrs;
#

So my question is

#

Why does balanceList not print

#

When it has been defined outside the query.forEach()

#

Shouldn't changes to value of balanceList inside the iteration be maintained?

naive token
#

You mean it's not printing it or prints an empty object?

#

I guess you should use await Promise.all() + query.map() instead of .forEach, because it doesn't care about promises returned from async callback

#

Or just switch to for..of

mint forge
#

No, it does not print anything

#

Is it cause that part of the code never gets executed?

#

the last 2 lines

#

inside the func

naive token
mint forge
#

I can't think of any error, the array 'query' is a very simple mongodb returned dictionary

naive token
#

Try rewriting to this:

async function getAddrs() {
    try {
      const query = await client.db('users').collection('userAddress').find().toArray()
      let balanceList= {}

      for (const entry of query) {
          const username = await entry['username'];
          const mnemonic = await entry['address']['mnemonic']
          const address = await genSegWallet(mnemonic)
          const addressArr = Object.values(address)
          balanceList[username] = {}
  
          for (const [index, addr] of addressArr.entries()) {
              // const bal = await getBal(addr);
              const bal = 0;
              cursor[username][index] = { 'address': addr, 'balance': bal }
          }
        console.log(balanceList) //This prints 3 times cause there are 3 elements in the query array.
      }

      console.log(balanceList) //Does not print
    } catch (e) { console.error('error:', error); }

    return cursor;
}
mint forge
#

Okay

#

@naive token

naive token
#

Where is that log coming form?

mint forge
#

I was using BTCt instead of BTC. It gives a warning for test coins

#

Removing that

naive token
#

Where do you call getAddrs function?

#

I don't see this log

mint forge
#

oh wait hang on

#

I should shoot myself in the foot. I spent 8 minutes trying to figure out whats wrong with the code, and then realised that i didn't call the function 🤣

naive token
#

😛

#

So why do you put a comment that it's logged 3 times?

mint forge
#

Because it does

naive token
#

...after it's actually called 👀

mint forge
#

yes xD

#

So it prints the dictionary

#

but its empty

naive token
#

Do you still use forEach of is it with for..of?

#

Also, i don't see you are updating balanceList there; and where cursor variable is coming from?

mint forge
#

Before I pasted the code, I renamed cursor to balanceList

#

I missed a few places

mint forge
#

But used your

#

and it's amazing

#

Why doesn't the process exit though?

naive token
trail agate
#

process.exit(0) is more explicit and less imperative seemsgood

trail agate
trail agate
naive token
trail agate
naive token
#

True 👍

mint forge
mint forge
#

But I will only know for sure when I get to the phase where I need to implement it

trail agate
#

Whereas closing the conn when done is cleaner

mint forge
#

If I will be quering the mongo db every 5 minutes, it would be recommended to keep the connection open and then just add a timeout fucntion to call the query function right?

trail agate
#

But then you don't want it to close :)

mint forge
#

I'll read up more about it

trail agate
mint forge
#

@trail agate Thank you CB_dance_kanna