Node.js 和 oracledb 的问题

Problems with Node.js and oracledb

我在使用 node.js 脚本时遇到问题(顺便说一句,我对 node 还是很陌生)。当我 运行 通过 forEach 循环时,似乎它可能是 运行ning 异步,因此不是 运行ning 问题。但是,当我查看包文档时,我没有看到任何有关将 sql 执行同步到 运行 的信息。在此先感谢您的帮助!

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";
    }
  });
});

当脚本 运行s 时,我希望看到如下内容:

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

然而,我最终得到的是:

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

有什么想法吗?谢谢!

基本选项的简要说明:

回调

使用像 https://github.com/caolan/async 这样的包来轻松管理回调的“for 循环”。 (还有其他套餐)

forEach 不会等待你的回调完成,这就是为什么它们同时都是 运行 的原因。您还可以通过使用带有迭代器的回调来管理您自己的 for 循环,该迭代器在达到最大迭代器时停止。

但您也可以使用 :

require('util').promisify 转换 node.js 风格的回调函数

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

一个承诺,然后您可以执行以下操作:

承诺

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

Async/Await

或者您可能想要的...

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);
    }
  }
}