ForEach works strangely for an array in JS. What to do?

  • 0
    Good afternoon! I tested authorization and came across such a miracle that the function contains an array and its iteration (forEach). Search is provided in the search and it is actually written to the log that something was found. There is a return, which, in theory, should complete the execution of the function, but the code is also executed after the iteration.

    Here's the function itself:
    Function code

    async search(login) {
            fs.readFile(`${__dirname}/data/users.json`, (err, data) => {
                if(err) return false
                // Convert to JSON
                let parsed = JSON.parse(data.toString())
                // If user found, return functions. If not - true (data is correct, but user not exists)
                parsed.forEach((user, i) => {
                    console.log('Parsing users. Index', i, 'Data:', user)
                    console.log(`${user.auth.login} = ${login},`, user.auth.login === login)
                    if(user.auth.login === login) {
                        console.log('All ok')
                        return {
                            validPassword: password => {
                                return user.auth.password === argon.hash(crypt.decrypt(password, 'smthkey').toString()).toString()
                            getProfile: () => {
                                return user.profile
                            getID: () => {
                console.log('Nothing is found')
                return true

    JavaScript Anonymous, May 16, 2019

  • 4 Answers
  • 0
    There is a return, which, in theory, should terminate the execution of the function

    What the hell is this?

    Note: There is no way to stop or interrupt a forEach () loop other than by throwing an exception. If you need this behavior, the forEach () method is the wrong choice.

  • 0
    return fires and returns control from the anonymous function to the main forEach loop, after which forEach works further.

    Use .find

  • 0
    these are retracts for arrow functions, for example this

    password => {
    return user.auth.password===argon.hash(crypt.decrypt(password, 'smthkey').toString()).toString()
    Blake Nunez

  • 0
    A bunch of code notes.

    1. If async is used, why not use fs-promises?

    const fs = require ('fs'). promises

    2. Why do data.toString () if you can specify an encoding and a string will be returned immediately, not a buffer?

    fs.readFile (file, 'utf-8')

    3.all this sheet can be rewritten to a regular find

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!