0

I'm having a problem with a node.js script at work (I'm pretty new to node in general, btw.). When I run through the forEach loop, it appears that it might be running asynchronously and therefor is not running problem. However, when I looked through the package documentation, I didn't see anything about get the sql execution to run synchronously. Thanks in advance for the help!

function getLastLoginAndProviderType(jsonObj, connection){
console.log(jsonObj);
jsonObj.forEach(obj => {
console.log("Processing: " + obj["email"]);
//obj["email"], obj["first"], obj["last"], obj["eid"], obj["role"] 

var sql = "select LAST_LOGGED_IN_TIME from EINV_OWNER.CONTACT where EMAIL_ADDRESS='" + obj['email'] + "'";

connection.execute(
  sql, {}, { maxRows: 15 },
  function(err, result) {
    if (err) {
      console.error("Query Error: " + err.message);
    } else {
      console.log("Number of rows returned: " + result.rows.length);

      obj["lastLoggedIn"] = "null";
      obj["supplierOrProvider"] = "null";
    }
  });
});

When the script runs, I would expect to see something like:

Processing: XXX@XXX.com
Number of rows returned: XX
Processing: XXX@XXX.com
Number of rows returned: XX
...
Processing: XXX@XXX.com
Number of rows returned: XX

However, what I end up getting is:

Processing: XXX@XXX.com
Processing: XXX@XXX.com
Processing: XXX@XXX.com
...
Processing: XXX@XXX.com
Query Error: NJS-003: invalid connection
Query Error: NJS-003: invalid connection
Query Error: NJS-003: invalid connection
...
Query Error: NJS-003: invalid connection

Any ideas? Thanks!

MT0
  • 143,790
  • 11
  • 59
  • 117
jhammond
  • 1,916
  • 2
  • 15
  • 29

1 Answers1

0

Quick rundown on the basic options:

Callbacks

use package like https://github.com/caolan/async to easily manage a "for loop" of callbacks. (there are other packages)

forEach does not wait for your callback to complete, which is why they are all running at the same time. You can also manage your own for-loop by using a callback with an iterator that stops when the max iterator is reached.

But you could also use :

require('util').promisify to convert a node.js styled callback function

myFn(foo,bar,<function(err,data){}>) 

to a promise which then you can do the following:

Promises

Resolve promises one after another (i.e. in sequence)?

Async/Await

Or what you probably would want...

async function myFunction(){
  for(i=0;i<jsonObj.length;i++){
    try{
      let result = await connection.execute(sql, {}, { maxRows: 15 })
      console.log("Number of rows returned: " + result.rows.length);
      obj["lastLoggedIn"] = "null";
      obj["supplierOrProvider"] = "null";
    }catch(e){
      console.error("Query Error: " + err.message);
    }
  }
}
Community
  • 1
  • 1
Cody G
  • 8,368
  • 2
  • 35
  • 50