Justin Yapp
Justin Yapp

Reputation: 89

mssql nodejs: Using a connection pool throughout a promise chain

I am using the mssql library for nodejs to make queries to my Microsoft SQL Database. It first checks if a row exists in the database and if it does, update the values of that row, if not, create a new row. Here is how I have it set up. When executed, it complains that the variable pool does not exist on lines 35 and 38.

How can I use the pool variable which i got from the first then statement, in the third then statement.

enter image description here

Upvotes: 1

Views: 1087

Answers (1)

Dan D.
Dan D.

Reputation: 74655

The issue is that your three latter thens need to be inside your first then. That way the pool is in their scope.

The pattern is:

sql.connect(config).then(pool => { 
  pool.request.query().then().then().then();
})

Can you not use a "insert if not exists"? This would be atomic and race free. See SQL Server Insert if not exist If you used this you would only have to handle the case where the row already exists

Upvotes: 2

Related Questions