Using finally() to correctly construct a Javascript promise

Currently, I am working on an Express API that utilizes the mssql package.

If I neglect to execute sql.close(), an error is triggered displaying:

Error: Global connection already exists. Call sql.close() first.

I aim to keep the endpoints simple and easy to manage by implementing a promise pattern using finally.

const sql    = require("mssql")
const config = require("../config")

sql.connect(config.properties).then(pool => {
  return pool.request()
    .execute('chain')
    .then(response => {
      res.send(response['recordsets'][0][0]['response'])
    })
    .catch(err => res.send(err))
    .finally(sql.close())
})

Unfortunately, the above code results in the following error:

{ "code": "ENOTOPEN", "name": "ConnectionError" }

The following code does work, but it seems inefficient to repeatedly define sql.close within the same function.

sql.connect(config.properties).then(pool => {
  return pool.request()
    .execute('chain')
    .then(response => {
      res.send(response['recordsets'][0][0]['response'])
      sql.close()
    })
    .catch(err => {
      res.send(err)
      sql.close()
    })
})

Is there a better way to incorporate calling sql.close after either sending a response or an error with res.send?

Answer №1

When using .finally in a function, you are passing the result of that function.

sql.connect(config.properties).then(pool => {
  return pool.request()
    .execute('chain')
    .then(response => {
      res.send(response['recordsets'][0][0]['response'])
    })
    .catch(err => res.send(err))
    .finally(() => sql.close()) // CORRECTED HERE
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why am I unable to alter the variable value within the callback event?

Exploration of Request Handling POST request To /api/endpoint headers: standard body: data=test123 POST response From /api/endpoint headers: standard body: data=test123 expectation(NOT MET): Show the request body content in the console. reality(FRU ...

Having trouble retrieving the JSON response in Express using Axios on localhost

I am currently developing an express app that utilizes axios. While it functions properly in production, I am encountering difficulties when testing it on localhost - specifically, I am unable to retrieve the response data. app.post('/login', fun ...

Using AngularJS, I can bind the ng-model directive to asynchronously update and retrieve data from

I am currently working with Angular to develop a preferences page. Essentially, I have a field in a mysql table on my server which I want to connect my textbox to using ng-model through an asynchronous xhr request for setting and fetching data. I attempt ...

Using PHP to send asynchronous requests to the server can greatly enhance

I have almost completed my project, but I am facing an issue with reading the data sent to the server. function main() { jQ(document).on("keyup", "form input", function () { var data = new FormData(); var value = jQ(this).val(); da ...

Leverage ESlint for optimal code quality in your expressjs

Is there a way to use ESlint with Express while maintaining the no-unused-vars rule? After enabling ESlint, I am encountering the following issue: https://i.stack.imgur.com/7841z.png I am interested in disabling the no-unused-vars rule exclusively for e ...

Can I access properties from the index.html file within the Vue.js mount element?

<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="widt ...

Showcase images from a MongoDb database in an HTML document

Currently, I am utilizing Node.js with mongoose and EJS as the view engine. I have successfully created a simple send command to retrieve and send images on the server side by following these helpful guides: Setup file uploading in an Express.js applicat ...

Verify if the screen is in full view by monitoring document.fullscreenElement within Vue3

Is there a way to determine when the document is in fullscreen mode? I attempted to monitor document.fullscreen with the following code, but it was not successful: watch(document.fullscreenElement, (newValue) => { fullScreenActivated.value = newValue ...

What steps can be taken to sustain a Cloud Functions connection while utilizing ExpressJS?

const http = require('http'); const functions = require('firebase-functions'); const agent = new http.Agent({keepAlive: true}); exports.function = functions.https.onRequest((request, response) => { req = http.request({ h ...

When I attempt to press the shift + tab keys together, Shiftkey is activated

Shiftkey occurs when attempting to press the shift + tab keys simultaneously $("#buttonZZ").on("keydown",function (eve) { if (eve.keyCode == 9 && eve.shiftKey) { eve.preventDefault(); $("#cancelbtn").focus(); } if (eve. ...

Delivering compressed files in a React server

Having some trouble serving a gzip compression of my bundle.js file in React. Have tried reducing the size with uglify and dedupe, but only saw a small decrease from 2.9mb to 2.6mb. Using the compression plugin now outputs a gzip file, however, still servi ...

Working with extensive amounts of HTML in JavaScript

Is there a way to dynamically load large amounts of HTML content in JavaScript? I'm struggling to figure out how to insert all the HTML content into the designated space within the JavaScript code. If anyone knows a different approach or solution, ple ...

Angular-datatables has a scroller function that allows for easy navigation within the content of

I've been scouring the web for hours, but I can't seem to find a solution. Can someone please assist me in resolving this issue? Issue: I integrated angular-datatables within an md-tab using Angular material. Everything was running smoothly unti ...

Resolving the Issue of Jerky Graphics During HTML5 Canvas Animation

When animating a layer in canvas, the visual quality becomes uneven if there are additional layers present. You can see an example of this by clicking "RUN" on this fiddle: http://jsfiddle.net/Q97Wn/ If I modify this line: opts.percentageIndicator.clearR ...

Mastering the use of node cluster mode in conjunction with agenda cronjobs

Currently, I am utilizing nodejs and agenda to run cronjobs. With a total of 10 cronjobs in place, the process is taking longer as nodejs is single-threaded and they all run simultaneously. In an attempt to resolve this issue, I experimented with pm2 by e ...

Unable to call a basic object's prototype method

Just starting out with node and feeling like I might be overlooking something simple. In my model file, I have a class that creates new object instances in the following way: const mongodb = require('mongodb'); const getDb = require('../util ...

Looking to keep your data up to date instantly? Harness the power of Socket.IO for

I have successfully developed a web application using nodejs, express, and mongodb. For practice, I created a twitter-like platform where users can post tweets that will appear on their profile and the feeds of their followers. The homepage displays post ...

Issues with managing ajax response handlers

Just dipping my toes into the world of ajax and attempting to create a reusable ajax request function. According to Firebug, the request is successfully fetching the correct data from my php file. However, for some reason, the response isn't getting i ...

Creating a dynamic state management system for multiple Collapse components can be achieved by utilizing

I am trying to create a Collapse menu from array data, Currently, when I click on any menu all sub menus expand I believe my issue lies in not being able to set a unique "open" state for each Main menu I want to avoid assigning a "state" to accommodate ...

Utilizing a PHP-scripted multidimensional array in an AJAX success function

I've encountered an issue while trying to access a multidimensional array passed to my AJAX success function. Here's how I'm sending the data: $response = array(); $response['message']['name'] = $name; $response['m ...