Array populated in debug more but not in in normal mode in Node.js - arrays

In the code below, when I run in debug mode with a break-point at this line: content.push(data.Body.toString()); I can see that data is inserted to the content array.
However when I run the code normally, content comes back empty.
How can I get it to populate the array for downstream use?
var params = { Bucket: "thebucket", Prefix: "theprefix/" }
var content = [];
function getS3Data()
{
var s3 = new aws.S3();
s3.listObjects(params, function (err, data)
{
if (err) throw err; // an error occurred
else
{
var i;
for (i = 0; i < data.Contents.length; i++)
{
var currentValue = data.Contents[i];
if(currentValue.Key.endsWith(params.Prefix) == false)
{
var goParams = { Bucket: params.Bucket, Key: currentValue.Key };
s3.getObject(goParams, function(err, data)
{
if (err) throw err; //error
content.push(data.Body.toString());
});
};
};
}//else
});//listObjects
}//getS3Data
getS3Data();
console.log(content); //prints empty here when run in non-debug.

The line:
console.log(content)
is being executed before the line:
content.push(data.Body.toString());
the function you are passing as a 2nd argument to s3.listObjects will be executed asynchronously. If you want to log out content you need to do it within the callback function meaning:
s3.listObjects(params, function (err, data) {
if (err) throw err;
else {
// ...
console.log(content)
}
});
A better approach would be to implement getS3Data with Promise so you can run code after the object listing is done for sure.
function getS3Data() {
return new Promise((resolve, reject) => {
if (err) {
reject(err)
} else {
const promises = []
for (const i = 0; i < data.Contents.length; i++) {
const currentValue = data.Contents[i];
if (currentValue.Key.endsWith(params.Prefix) == false) {
const goParams = { Bucket: params.Bucket, Key: currentValue.Key };
promises.push(new Promise((res, rej) => {
s3.getObject(goParams, function (err, data) {
if (err) {
rej(err); //error
} else {
res(data.Body.toString());
}
});
}));
}
}
Promise.all(promises).then(resolve);
}
});
}
getS3Data()
.then(result => { // this will actually be `content` from your code example
console.log(result);
}).catch(error => {
console.error(error);
})

Node.js' documentation has an example very similar to the problem you are experiencing:
Dangers of Mixing Blocking and Non-Blocking Code
The issue arises because the variable content is not set as soon as getS3Data has finished, because it is an asynchronous function. content will be set some time later. But your call to console.log(content); will execute immediately after getS3Data has finished, so at that point content has not been set yet.
You can test that by adding an extra log:
s3.getObject(goParams, function(err, data)
{
if (err) throw err; //error
content.push(data.Body.toString());
console.log("Content has been assigned");
});
And then change the bottom to:
getS3Data();
console.log("getS3Data has finished", content);
It's likely you'll get the messages in this order:
getS3Data has finished
Content has been assigned

Related

How to Run an API Calls in Parallel (Node.js)

I am trying to run some API calls in parallel, but am having problems since I am trying to call a function again before the API data has been returned.
I am thinking that I could possibly use the new command in Node, but am not sure how to structure it into this scheme. I am trying to avoid recursion, as I already have a recursive version working and it is slow.
Currently I am trying to this code on the server.
loopThroughArray(req, res) {
for(let i=0; i<req.map.length; i++) {
stack[i] = (callback) => {
let data = getApi(req, res, req.map[i], callback)
}
}
async.parallel(stack, (result) => {
res.json(result)
})
}
....
function getApi(req, res, num, cb) {
request({
url: 'https://example.com/api/' + num
},
(error, response, body) => {
if(error) {
// Log error
} else {
let i = {
name: JSON.parse(body)['name'],
age: '100'
}
console.log(body) // Returns empty value array.length > 1 (req.map[i])
cb(i)
}
})
Is there a way to spawn new instances of the function each time it's called and accumulate the results to send back as one result to the client?
Here's an example of calling Web APIs (each with different parameters), using the Async library, we start by creating an array of N function variables.
const async = require('async');
const request = require('request');
//Set whatever request options you like, see: https://github.com/request/request#requestoptions-callback
var requestArray = [
{url: 'https://httpbin.org/get'},
{url: 'https://httpbin.org/ip'}
];
let getApi = function (opt, callback) {
request(opt, (err, response, body) => {
callback(err, JSON.parse(body));
});
};
const functionArray = requestArray.map((opt) => {
return (callback) => getApi(opt, callback);
});
async.parallel(
functionArray, (err, results) => {
if (err) {
console.error('Error: ', err);
} else {
console.log('Results: ', results.length, results);
}
});
You can easily switch the Url and Query values to match whatever you need. I'm using HttpBin here, since it's good for illustrative purposes.

Promises not running T-SQL query in node js

I am trying to write a function in node js that will run a SQL query using mssql and return a promise. For some reason it gets to the line
console.log("got to the run proc functions");
but won't run any code after that. Any help with this issue would be greatly appreciated.
runProc: function (params) {
var sql = require("mssql");
sql.Promise = require('promise');
return new Promise((resolve, reject) => {
var dbConfig = {
server:"ip",
database: "db",
user:"user",
password: "pw"
}
console.log("got to the run proc functions");
var keys = Object.keys(params);
sql.connect(dbConfig).then(pool => {
console.log("got connected");
const request = pool.request()
for (var i = 0; i < keys.length; i++) {
if (keys[i].substring(0,6)=="Common") {
request.input(keys[i],sql.Bit,params[keys[i]]);
console.log("set the bit parameters");
}
else {
request.input(keys[i],params[keys[i]]);
console.log("set the other parameters");
}
}
request.execute("storedprocedure")
return request;
}).then(result => {
resolve(result)
}).catch(err => {
reject(Error(err))
});
sql.close();
});
}
Look where you call sql.close(). i.e. it's being called before request=pool.request etc! So, that would fail for a start.
Also, you are returning request (which isn't a promise) rather than request.execute() (which is a promise) so, the promise would resolve before execute completes
And finally, no need to wrap a promise inside a Promise constructor (not that this breaks your code, but there's no need for it)
Given all that, your code is
runProc: function (params) {
var sql = require("mssql");
sql.Promise = require('promise');
// removed new Promise constructor as sql.connect already returns a promise we can chain to and return
var dbConfig = {
server:"ip",
database: "db",
user:"user",
password: "pw"
}
console.log("got to the run proc functions");
var keys = Object.keys(params);
return sql.connect(dbConfig)
.then(pool => {
console.log("got connected");
const request = pool.request()
for (var i = 0; i < keys.length; i++) {
if (keys[i].substring(0,6)=="Common") {
request.input(keys[i],sql.Bit,params[keys[i]]);
console.log("set the bit parameters");
}
else {
request.input(keys[i],params[keys[i]]);
console.log("set the other parameters");
}
}
// need to return the result of execute, not the request object
return request.execute("storedprocedure")
})
.catch(err => throw new Error(err))
// use Promise#finally - available in all good promise libraries
.finally(sql.close); // sql.close AFTER we're done with it, not before
}
Using the sparkly new async/await promise sugar simplifies the code even more
runProc: async function (params) {
var sql = require("mssql");
sql.Promise = require('promise');
var dbConfig = {
server:"ip",
database: "db",
user:"user",
password: "pw"
}
console.log("got to the run proc functions");
var keys = Object.keys(params);
try {
const pool = await sql.connect(dbConfig);
const request = pool.request();
for (var i = 0; i < keys.length; i++) {
if (keys[i].substring(0,6)=="Common") {
request.input(keys[i],sql.Bit,params[keys[i]]);
console.log("set the bit parameters");
}
else {
request.input(keys[i],params[keys[i]]);
console.log("set the other parameters");
}
}
// need to return the result of execute, not the request object
return await request.execute("storedprocedure");
} catch (err) {
throw new Error(err);
} finally {
sql.close();
}
}

node mssql stream return issue

I am attempting to stream the data from a procedure that returns multiple data sets using node and mssql. If using as a stand a long function it works, but I need it to return the dataset from the route i am using.
handler: function(request, reply) {
var inputValues = request.payload.inputParams;
var procName = request.params.procedureName;
var request = new sql.Request(mainsettings.connection);
request.stream = true;
var newGroup = [];
var count = 0;
var recordSetArr = [];
for(var key in inputValues) {
var currentParam = inputValues[key];
var paramType = getParamType(sql, currentParam.paramType);
try {
request.input(currentParam.paramName, paramType, currentParam.paramValue);
}
catch(err) {
console.error(err);
}
}
request.execute(procName);
request.on('recordset', function(columns) {
// Emitted once for each recordset in a query
count++;
if(count > 1) {
recordSetArr.push(newGroup);
}
newGroup = [];
});
request.on('row', function(row) {
// Emitted for each row in a recordset
newGroup.push(row);
});
request.on('error', function(err) {
// May be emitted multiple times
console.error(err);
});
request.on('done', function(returnValue) {
// Always emitted as the last one
return (recordSetArr);
});
}
I am getting the following error.
Debug: internal, implementation, error
Error: handler method did not return a value, a promise, or throw an error
at module.exports.internals.Manager.execute (F:\FARA_API\node_modules\hapi\l
ib\toolkit.js:52:29)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
180406/194833.505, (1523044113505:MISOM-DEV-002:6976:jfod4ysa:10140) [error] mes
sage: handler method did not return a value, a promise, or throw an error, stack
: Error: handler method did not return a value, a promise, or throw an error
at module.exports.internals.Manager.execute (F:\FARA_API\node_modules\hapi\l
ib\toolkit.js:52:29)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
Any suggestions on how I am supposed to return the data set properly?
Also tried the following
handler: function(request, reply) {
recordRouteCall("procedure");
var inputValues = request.payload.inputParams;
var procName = request.params.procedureName;
sql.connect(mainsettings.connection, err => {
var request = new sql.Request();
request.stream = true;
var newGroup = [];
var count = 0;
var recordSetArr = [];
for(var key in inputValues) {
var currentParam = inputValues[key];
var paramType = getParamType(sql, currentParam.paramType);
try {
request.input(currentParam.paramName, paramType, currentParam.paramValue);
}
catch(err) {
console.error(err);
}
}
request.execute(procName);
request.on('recordset', columns => {
// Emitted once for each recordset in a query
count++;
if(count > 1) {
recordSetArr.push(newGroup);
}
newGroup = [];
});
request.on('row', row => {
// Emitted for each row in a recordset
newGroup.push(row);
});
request.on('error', err => {
// May be emitted multiple times
console.error(err);
});
request.on('done', result => {
// Always emitted as the last one
console.log(recordSetArr);
return (recordSetArr);
});
});
sql.on('error', err => {
console.error(err);
return err;
});
}

return bool value from middleware to express controller

I want to return a boolean value from middleware defined as
module.exports = {
authenticatepracticename: function(pname) {
ecollection.find({ $and: [{'name':pname},{'status' : 'active'}] }).exec(function (err, result) {
if (err) return false;
if(result.length == 1){
// console.log('true');
return true;
}
else{
// console.log('false');
return false;
}
});
},
// ...
}
to my express controller defined as
exports.checkcredentails = function (req, res) {
var result = practice.authenticatepracticename(practiceName);
}
but result is coming undefined even though middleware function is getting called.
The reason why you are getting undefined result from practice.authenticatepracticename is because ecollection.find performs asynchronous action and authenticatepracticename end without returning any value (which is undefined in JavaScript).
In order to improve that, you would need to provide a callback function from your checkcredentails to authenticatepracticename.
Example:
exports.checkcredentails = function (req, res) {
practice.authenticatepracticename(practiceName, function(err, result){
// you can handle error and result here e.g. by sending them back to a customer
res.send("Result: " + result);
});
}
And your authenticatepracticename:
authenticatepracticename: function(pname, cb) {
ecollection.find({ $and: [{'name':pname},{'status' : 'active'}] }).exec(function (err, result) {
if (err) return cb(err)
if(result.length == 1){
// console.log('true');
cb(null, true)
}
else {
// console.log('false');
cb(null, false)
}
});
}
I hope that will help.

Adding to an array asynchronously in Node.js

I'm pretty new to this type of programming and I'm having some trouble populating an array from a nested call. I'm pretty sure this needs to be done using callbacks, but I'm having trouble wrapping my brain around it. Closures must also come into play here. I tried searching the web for a similar example but didn't find much.
Here is my original code. I tried a few different approaches but didn't pull it off.
TaskSchema.statics.formatAssignee = function(assignees) {
var users = [];
assignees.forEach(function(uid) {
mongoose.model('User').findById(uid, function(err, user) {
users.push({
name: user.name.full
, id: user.id
});
});
});
return users;
}
I really like the following pattern (recursion is the most elegant solution to async loops):
TaskSchema.statics.formatAssignee = function(assignees, callback) {
var acc = []
, uids = assignees.slice()
(function next(){
if (!uids.length) return callback(null, acc);
var uid = uids.pop()
mongoose.model('User').findById(uid, function(err, user) {
if (err) return callback(err);
acc.push({
name: user.name.full
, id: user.id
});
next();
});
})();
}
Check out async, it has an async foreach loop.
Edit
Here is the foreach method from the async library
async.forEach = function (arr, iterator, callback) {
if (!arr.length) {
return callback();
}
var completed = 0;
_forEach(arr, function (x) {
iterator(x, function (err) {
if (err) {
callback(err);
callback = function () {};
}
else {
completed += 1;
if (completed === arr.length) {
callback();
}
}
});
});
};
var _forEach = function (arr, iterator) {
if (arr.forEach) {
return arr.forEach(iterator);
}
for (var i = 0; i < arr.length; i += 1) {
iterator(arr[i], i, arr);
}
};
you could do something like:
Give formatAssignee a callback.
Count down how many users you need to push onto users.
After you push the last one, invoke the callback with the parameter users.

Resources