Monday 13 November 2017

How to perform some synchronous stuff

I learned that a big part of node is asynchronous. Are there ways to handle things synchronously? For example, can we wait until a database request is complete and then do something else? Like, store the result in a variable?In some cases, the object/array returned by the database result is not how I want it and so I have to build an object according to my preference. In other cases, where a loop is involved and inside the loop, there is async happening and unable to store the data returned outside of the loop.1st example.app.get('/dbstuff', function(req, resp) { var results = []; connection.connect(function(err) { db.query('SELECT * FROM employee', function(err, result) { for (let item of result.recordset) { results.push(item); // don't ask me why I would do this, I just want to know if it's possible } }); } console.log(results); // undefined }); 2nd examplesomeModule.emloyees(err, employees) { // a module that gets all employees var empId = [1, 4, 6]; // the employees I want to return var emp = {}; for (let employee of employees) { if (empId.indexOf(employee.id) >= 0) { someModule.employee(employee.id).get('name', 'department', function(err, emp) { // this is happening async emp['name'] = emp.fields.name; emp['dept'] = emp.fields.department; }); } // sadly, I cannot resp.send here so I have to build my obj } console.log(emp); // but it's undefined }); This would be useful for those who are also learning node.

Submitted November 13, 2017 at 10:52AM by eggtart_prince

No comments:

Post a Comment