digininja icon

Nodejs SQL scope

digininja | PRO | 03/08/20 06:15:02 PM UTC | 0 ⭐ | 516 👁️ | Never ⏰ | []
JavaScript |

970 B

|

None

|

0 👍

/

0 👎

/*
I want this code to return the array of students that is generated by going through the SELECT statement.
Due to db.each going off on its own thread, the `students` array it populates is in a different scope
to the one I declare which is returned empty before the db.each finishes.
 
How do I get the `return` to return the data?
*/
 
 
    searchStudents: ({term}) => {
 
        var lessons = ['maths', 'English'];
        var students = []; 
 
        console.log (students);
            db.each(`SELECT * FROM students`, (err, row) => {
                if (err) {
                    console.error(err.message);
                } else {
                    student = new Student (row.id, row.name, lessons, row.password, row.attendence);
                    students.push (student);
                    console.log(row.id + "\t" + row.name + "\t" + row.password);
                }   
            }); 
        console.log (students);
 
        return students;
    }

Comments