每个都有异步的SQL查询

时间:2017-02-26 11:00:30

标签: sql node.js asynchronous

我的问题是当我获得一组用户并尝试运行异步时,每次启动每个sqlRequest而不是逐个推送数组。

它应该逐个执行sqlRequest,而不是每个用户执行sqlRequest和数组中的推送。

这是每个

的异步
function getUserFavCat(params, callback) {
  var usersArrayCat = [];
  async.each(params, function (user, cb) {
    sqlRequest("SELECT b_cat.title, b_cat.id FROM dbo.Students st INNER JOIN dbo.SaleView sv ON sv.userId = st.id INNER JOIN dbo.KEY_BrandcategoryToSale b_key ON b_key.saleId = sv.saleId INNER JOIN dbo.BrandCategories b_cat ON b_cat.id = b_key.brandCategoryId WHERE st.id = " + user.id, function (err, result) {
      if (!result) {
        //console.error("NO FAVOURITE CATEGORY FOR USER " + JSON.stringify(user))
      } else if (result.length == 0) {
        //console.error("NO FAVOURITE CATEGORY FOR USER " + JSON.stringify(user))
      } else {
        user.favouriteCat = utils.takeMostRepeatingObj(result);
        usersArrayCat.push(user);
      }
      cb();
    })
  }, function() {
    callback(null, usersArrayCat)
  });
};

这是SQL查询:

function sqlRequest (sqlQuery, callback) {
  var connection = new sql.Connection(sql_conf, function (err) {
    if (err){
      console.log(err)
    } else {
      var request = new sql.Request(connection);
      request.query(sqlQuery, function(err, result) {
        console.log(result)
        if(err){
          console.error(err)
        } else if(!result){
          console.error("NO RESPONSE SQL QUERY")
        } else {
          callback(null, result);
          connection.close();
        }
      })
    }
  });
  connection.on('error', function(err) {
    console.log(err);
  });
};

2 个答案:

答案 0 :(得分:1)

使用async.eachLimit来限制号码。请求

function getUserFavCat(params, callback) {
    var usersArrayCat = [];
    console.log(`length of array ${params.length}`)
                        // 1 here means 1 request at a time
    async.eachLimit(params, 1, function (user, cb) {
        sqlRequest("SELECT b_cat.title, b_cat.id FROM dbo.Students st INNER JOIN dbo.SaleView sv ON sv.userId = st.id INNER JOIN dbo.KEY_BrandcategoryToSale b_key ON b_key.saleId = sv.saleId INNER JOIN dbo.BrandCategories b_cat ON b_cat.id = b_key.brandCategoryId WHERE st.id = " + user.id, function (err, result) {
            if (!result) {
                //console.error("NO FAVOURITE CATEGORY FOR USER " + JSON.stringify(user))
            } else if (result.length == 0) {
                //console.error("NO FAVOURITE CATEGORY FOR USER " + JSON.stringify(user))
            } else {
                user.favouriteCat = utils.takeMostRepeatingObj(result);
                usersArrayCat.push(user);
                cb();
            }
        })
    }, function (err) {
        if (err) return callback(err);
        callback(null, usersArrayCat)
    });
};

答案 1 :(得分:0)

使用async.map尝试此技巧,并推送每个回调数组。然后你可以使用async.parallel过滤掉成功用户的回调结果并将其推送到usersArrayCat数组

function getUserFavCat(params, callback) {
  var usersArrayCat = [], callbackArrays = [];
  async.map(params, function (user, cb) {
    callbackArrays.push(function (cb) {
       sqlRequest("SELECT b_cat.title, b_cat.id FROM dbo.Students st INNER JOIN dbo.SaleView sv ON sv.userId = st.id INNER JOIN dbo.KEY_BrandcategoryToSale b_key ON b_key.saleId = sv.saleId INNER JOIN dbo.BrandCategories b_cat ON b_cat.id = b_key.brandCategoryId WHERE st.id = " + user.id, function (err, result) {
       if (!result) {
         user.status = '99'; // error status
         cb(null, user);
       } else if (result.length == 0) {
         user.status = '99'; // error status
         cb(null, user);
       } else {
         user.favouriteCat = utils.takeMostRepeatingObj(result);
         user.status = '00'; //success status
         cb(null, user);
       }
     });
   }, function(err, results) {
     // comes here after all individual async calls have completed
     // check errors; array of results is in data
     cb(null, results)
   });

   async.parallel(callbackArrays, function (err, results) {
      results.forEach (function (elem, ind) {
        if (elem.status == '00') {
           usersArrayCat.push(elem);
        }
      });
   });
 };