1

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

Justin Yapp
  • 89
  • 1
  • 6
  • 1
    Please post your code and not an image of your code. This is easy to do and format properly: [How do I format my code blocks?](https://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks). More folks are likely to respond. Thanks – Jon Jaussi Dec 20 '18 at 20:49

1 Answers1

2

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

Dan D.
  • 73,243
  • 15
  • 104
  • 123