用Node.js和Tedious插入多条logging

我有一个客户对象数组,我想插入到SQL数据库。 客户对象从请求数据中检索。

我正在使用Tedious进行请求,并且Tedious Connectionpool为了同时有多个连接。

当循环播放对象时,我尝试插入时出现错误,错误是

{ [RequestError: Violation of PRIMARY KEY constraint `'PK__Customer__A4AE64D873A5400C'. Cannot insert duplicate key in object 'dbo.Customer'. The duplicate key value is (2).]` 

请注意,此时我只有3个对象正在发送请求。 它看起来只是最后一个被处理和插入的对象。 但是因为我对Node.js使用单调乏味,我不能发现我的错误。 有什么build议么 ?

 router.post('/',jsonParser, function(req, res) { var customers = req.body.customers; var companies = req.body.companies; var Connection = require('tedious').Connection; var Request = require('tedious').Request; var TYPES = require('tedious').TYPES; var config = { userName: '*************', password: '*************', server: '***********.database.windows.net', // When you connect to Azure SQL Database, you need these next options. options: {encrypt: true, database: '*******'} }; var poolConfig = { min: 1, max: 3, log: true }; var pool = new ConnectionPool(poolConfig, config); for (var i = 0; i < customers.length; i++) { console.log('Inserting '+customers[i].firstname); var firstname = customers[i].firstname; var count = i; pool.acquire(function (err, connection) { if (err) console.error(err); //use the connection as normal var request = new Request("INSERT INTO dbo.Customer" + " (Firstname,CustomerId)" + "VALUES" + " (@Firstname,@CustomerId);", function (err, rowCount) { if (err) console.error(err); console.log('rowCount: ' + rowCount); //release the connection back to the pool when finished connection.release(); }); request.addParameter('Firstname', TYPES.VarChar,firstname); request.addParameter('CustomerId', TYPES.Int, count); request.on('row', function (columns) { console.log('value: ' + columns[0].value); }); connection.execSql(request); }); pool.on('error', function (err) { console.error(err); }); } }); 

variablescountfirstName的范围是全局的。 当pool.acquire(函数get的执行完for循环已经完成并且插入了最后一个客户两次。一个可能的解决scheme是将一个匿名函数放在for循环中,例如(它不一定是匿名的)

 for (var i = 0; i < customers.length; i++) { (function(count, firstName) { ...do insert here... }(i, customers[i].firstname)); }