简体   繁体   中英

NodeJS Promise behaviour query

I was experimenting with Promise in nodejs to better understand how it works. I have partially working code, but I am not sure if I am using it correctly. My intention is to pass error or correct result back to caller function. This seem to get complicated with all these callbacks. Here is what I have so far.

//This is my main CALLER function
function query_mcafee_mssql_type(database, node_name, type) {
  return new Promise(function (fulfill, reject) {
    switch (type) {
      case "currentDefinitionDate":
          computeCurrentDefinitionResult(database, node_name)
          .then(function (result) {
            console.log('query_mcafee_mssql_type' + result);
            fulfill(result);
          });
          break;
    }
  });
}

function computeCurrentDefinitionResult(database, node_name) {

  return new Promise(function (fulfill, reject) {
    var leaf_sql_query = "SELECT * FROM "+  JSON.stringify(database)  +".dbo.EPOLeafNode WHERE NodeName=" + "'" + node_name + "'";
    query_mcafee_mssql(leaf_sql_query)
    .then(function (LeafNode) {
         if (LeafNode == undefined) {
          fulfill(LeafNode);
         } else {
          return LeafNode;
         }
    })
    .then(function (LeafNode) {
      console.log('computeCurrentDefinitionResult' + LeafNode);
      var product_properties_sql_query = "SELECT * FROM "+  JSON.stringify(database)  +".dbo.EPOProductProperties WHERE ParentID=" + "'" + LeafNode.AutoID + "'" + "AND ProductCode LIKE 'VIRUSCAN%'";
      return query_mcafee_mssql(product_properties_sql_query);
    })
    .then(function (ProductProperty) {
      if (ProductProperty == undefined) {
          fulfill(ProductProperty);
      } else {
          return ProductProperty;
      }
    })
    .then(function (ProductProperty) {
      fulfill(ProductProperty.DATDate);
    });
  });
}

function query_mcafee_mssql(sql_string) {
  return new Promise(function (fulfill, reject) {
    query_mssql(mcafee_config, sql_string)
    .then(function (sql_response) {
      fulfill(sql_response);
      console.log('query_mcafee' + sql_response);
    });
  });
}

function query_mssql(config, sql_string){
  return new Promise(function (fulfill, reject) {
    var connection = new sql.Connection(config, function(err) {
      // ... error checks 
      if (err) {
        console.log('connection to mssql has failed');
        //throw err;
        fulfill();
      } else {
        // Query 
        var request = new sql.Request(connection); 
        request.query(sql_string, function(err, recordset) {
          // ... error checks should go here :
          if (err) {
            console.log('requst query error');
            fulfill();
          } else {
            // output query result to console:
            //console.log(recordset);
            fulfill(recordset);
         }
        });
      } 
    });
  });
}

My main caller function is query_mcafee_mssql_type(). I use Promise to allow the execution of the query. Once that is done, if its an error, I would like "undefined" to returned else the correct result to returned to the caller.

As per my understanding, fulfill and reject callbacks decide the fate of Promise. The top most in call stack is function query_mssql(). My assumption was that once I call "fulfill" with result if success or return fulfill() empty if error.

The function above that is query_mcafee_mssql() which is oblivious to error or success and just passes on the result.

The function computeCurrentDefinitionResult() is where all the problem arises. I need to make two sql query one after the other. However if first query fails then I don't see any point in proceeding with next query that means

query_mcafee_mssql(leaf_sql_query)
        .then(function (LeafNode) {
             if (LeafNode == undefined) {
              fulfill(LeafNode);
             } else {
              return LeafNode;
             }
        })

I do not want rest of the .then to be executed as it does not make sense if LeafNode is undefined. I want to return the LeafNode value back to its caller. However if I return fulfill(), the code flow seem to move to next .then. If I use, reject(), the caller query_mcafee_mssql_type() .then block is not getting called. The relevant block is show below.

computeCurrentDefinitionResult(database, node_name)
              .then(function (result) {
                console.log('query_mcafee_mssql_type' + result);
                fulfill(result);
              });

- How can I return the actual result from computeCurrentDefinitionResult() ?? - Does all the functions need to return "Promise" to achieve what I am doing? - Why does the code patch not return from the function after "fulfill()" is called? - Is there a need to use "return" in these function blocks? Any help would be appreciated. Thanks.

From your code, I got a feeling that you have no idea about the correct usage of resolve and reject in Promise. Here is the right one.

function query_mssql(config, sql_string){
  return new Promise(function (resolve, reject) {
    var connection = new sql.Connection(config, function(err) {
      // ... error checks 
      if (err) {
        return reject(err);
      }
      // Query 
      var request = new sql.Request(connection); 
      request.query(sql_string, function(err, recordset) {
        // ... error checks should go here :
        if (err) {
            return reject(er);
        }
        // output query result to console:
        //console.log(recordset);
        resolve(recordset);
      });
    });
  });
}
//Then use it like this
query_mssql(config,sql_string)
.then(function(LeafNode){
    //query success
    console.log(LeafNode);
}).catch(function(er){
    //query failed,
    console.log(er);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM