How to stop code within nested callbacks and a foreach loop?

so currently I’m setting up a little nodejs database and I’m basically trying to get all user info (if the user exists) and do a callback returning the user’s info, if the user doesn’t exist then I return null. Basically my issue here is that when I do return callback(null) or return callback(userdata) return doesn’t stop code execution, resulting in 2 executions of the callback and invalid data. It could be due to the various callbacks that these return callback()‘s are nested in or the foreach loop, although if it is, I’m not sure how to fix it. Any help is greatly appreciated, thank you!

Here is the code:

const getUserInfo = (sessionToken, callback) => {
    return fs.readdir(__dirname + "/database/users", (err, files) => {
        if(err) return callback(null);
        return files.forEach((file, index) => {
            return fs.readFile(__dirname + "/database/users/" + file, "UTF-8", (err, data) => {
                if(err) return callback(null);
                try {
                    const parsedData = JSON.parse(data);

                    if(parsedData.sessionToken === sessionToken) return callback({ email: parsedData.email, username: parsedData.username, bought: parsedData.bought });
                    else if(index === files.length - 1) return callback(null);
                } catch {
                    return callback(null);
                }
            });
        });
    });
}

A little explanation for the code: this is a function that takes in a sessionToken, which is a random string of characters for the user’s current session, and a callback of course. It then reads the database/users directory to get all the users, then for every user in that directory it reads the file and try’s to parse the data through JSON, if it doesn’t work then of course it returns null, if it does work and the sessionToken matches then it executes the callback with all the necessary user information. If we get to the end of the list and none of the sessions matched then we come to the conclusion the user doesn’t exist.

194 thoughts on “How to stop code within nested callbacks and a foreach loop?”

  1. Pingback: sildenafil
  2. Pingback: sildenafil online
  3. Pingback: free viagra
  4. Pingback: viagra coupon
  5. Pingback: cialis pills
  6. Pingback: cialis online uk
  7. Pingback: cialis best price
  8. Pingback: buy cialis viagra
  9. Pingback: discount viagra
  10. Pingback: viagra rx online
  11. Pingback: cialis in canada
  12. Pingback: cialis usa
  13. Pingback: sildenafil 100mg
  14. Pingback: mint tadalafil
  15. Pingback: viagra buy online
  16. Pingback: sildenafil citrate
  17. Pingback: roman viagra
  18. Pingback: viagra tablet
  19. Pingback: viagra women
  20. Pingback: compra viagra
  21. Pingback: walgreens viagra
  22. Pingback: viagra or cialis
  23. Pingback: sildenafil teva
  24. Pingback: sildenafil pills
  25. Pingback: cialis online

Leave a Comment