2017-08-07 70 views
0

我实际上有一个问题,通过在循环中做很多查询 它似乎不工作,100%的时间只是查询数组中的最新数据。Nodejs在一个循环中的多个查询

CurrentSocket.biznessStatus.ListOfItemsToAdd = ["1", "4"];  
if(Object.keys(CurrentSocket.biznessStatus.ListOfItemsToAdd).length >= 1){ 
     for(var id in CurrentSocket.biznessStatus.ListOfItemsToAdd){ 
      var readedIt = CurrentSocket.biznessStatus.ListOfItemsToAdd[id]; 

      pool.getConnection(function(id, err, connection){ 
       if(err) throw err; 

       console.log("doAction of ListOfItemsToAdd for itemID -> "+readedIt); 

       connection.query("SELECT COUNT(*) AS it FROM users_biznesspanel WHERE user_id = ? AND ui_id = ?", [CurrentSocket.user_id, readedIt], function(err, result){ 
        if(err) console.log(err); 
        if(result[0]["it"] != 0){ 
         connection.query("UPDATE users_biznesspanel SET nb = nb + 1 WHERE user_id = ? AND ui_id = ?", [CurrentSocket.user_id, readedIt], function(err, result){ 
          connection.release(); 
          if(err) console.log(err); 
          console.log("Added item: "+readedIt); 
         }); 
        } 
        else{ 
         connection.query("SELECT type FROM items WHERE iid = ?", [readedIt], function(err, result){ 
          if(err) console.log(err); 
          var catInfo = getItemType(result[0]["type"]); 

          var insertItem = "INSERT INTO users_biznesspanel(user_id, ui_id, icat, iscat) VALUES(?, ?, ?, ?)"; 
          connection.query(insertItem, [CurrentSocket.user_id, readedIt, catInfo.cat, catInfo.scat], function(err, result){ 
           connection.release(); 
           if(err) console.log(err); 
           console.log("Inserted item: "+readedIt); 
          }); 
         }); 
        } 
       }); 
      }.bind(pool, id)); 
     } 
    } 
+0

您需要重构代码才能更好地使用控制流。该网站[callbackhell.com](http://callbackhell.com/)有一些关于如何操作的指南。 – Mekicha

回答

0

我建议你查询SQL在一个复杂的SQL,“当案”语法,你可以使用,例如:

而且我一直使用的NodeJS“sequelize”模块帮助我查询SQL。这会更安全,你可以专注于你的物流。