How can I wait for complete execution of For loop and then run next code?

Viewed 49
var token = [];
for (let i = 1; i <= offlineMembers.length; i++) {
    if (typeof(offlineMembers[i]) === 'string') {
        ddb.get({
            TableName: "DB",
            Key: {
                Username: offlineMembers[i]
            }
        }, (err, data) => {
            if (err || Object.keys(data).length === 0) {
                console.log(err);
            } else {
                token.push(data.Item.token)
            }
        })
    }
}
console.log(token)

This is my code.

It always logs out the token array as empty [].

How can I wait for the execution of for loop to end and then run the console.log command?

1 Answers

You can use async/await to accomplish this (as mentioned in most comments).

Example:

let populateToken = (async () => {
  const token = [];
  // For Loop
  return token;
 })
 
 const token = await populateToken();
 console.log(token);

Related