0

I am trying to get the array after it is filled in a function but it is empty when I print it out.

Code:

var usersList = [];
app.post('/submitLogin',function(req,res) {
    getUsersGroups();
    console.log(usersList);    
});

function getUsersGroups() {
    const users = new Promise((resolve, reject) => {
        dbConnection
        .getUsers()
        .then(data => {
            resolve(data)
        })
    });
    const groups = new Promise((resolve, reject) => {
        dbConnection
        .getGroups()
        .then(data => {
            resolve(data)
        })
    });
    Promise.all([users, groups])
    .then(data => {
        usersList = data[0];
        groupsList = data[1];
        console.log(usersList)
    });
}

However, the console.log in the getUsersGroups(), prints out the filled array but it is empty in the app.post('/submitLogin...')

Why is this happening assuming that getUsersGroups() runs before I try to print out the array?

2
  • You are not returning anything.Return the promise and the that within. Commented Oct 4, 2019 at 9:38
  • I have tried to return it but it is undefined when I print it out. Commented Oct 4, 2019 at 9:48

2 Answers 2

1

You are not observing the async execution of your db call. The console.log(usersList); happens BEFORE the db call, so it is empty.

You must adapt your code like this and post the code AFTER the db execution:

app.post('/submitLogin', function (req, res) {
  getUsersGroups().then((data) => {
    console.log(data)
    res.send(data.usersList)
  })
})

function getUsersGroups () {
  const users = new Promise((resolve, reject) => {
    dbConnection
      .getUsers()
      .then(data => {
        resolve(data)
      })
  })
  const groups = new Promise((resolve, reject) => {
    dbConnection
      .getGroups()
      .then(data => {
        resolve(data)
      })
  })
  return Promise.all([users, groups])
    .then(data => {
      console.log(data[0])
      return {
        usersList: data[0],
        groupsList: data[1]
      }
    })
}

I strongly suggest to don't change a global variable like usersList (that I removed from my example) because if you receive two request contemporaneously, the second one could overwrite the data of the first one and cause many side effect.

Sign up to request clarification or add additional context in comments.

3 Comments

Ok thanks, I am going to try that, but a question... What if I need to access to the usersList variable in other functions? Will I have to call getUsersGroups() each time I need the data?
No, but if you are developing a statefull API you must be aware of that and avoid conflicts if thay can happen. For example if the user list is based on a "customerKey" you can create a Map with key: customerKey and value userList. So the HTTP request send the customerKay to access a dedicated userList
I understand. I am not developing an API but it is good to know. I have tried your code and it works now. Thank you! :)
0
    app.post('/submitLogin', async function(req,res) {
    await getUsersGroups();
    console.log(usersList);    
});

try this

1 Comment

Still empty array and my code editor says await has no effect on the type of this expression

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.