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

The document.ready function does not seem to be functioning properly within an iframe

In the main page, there's an embedded iframe set up like this: <iframe src="facts.php" style="width:320px; height:500px; border:hidden" id="facts"> </iframe> Within that iframe, a jQuery function is implemented as follows: <script ty ...

Building Next.js with a designated maximum number of processes/threads

I've uploaded a fresh Next.js app to the cloud server using npx create-next-app. However, when I try to run the build script, the server throws an error 'pthread-create: Resource temporarily unavailable'. { "name": "next&quo ...

Guide to dynamically setting SCSS $variables in JavaScript after retrieving them from local storage in a React application

In my current situation, I am retrieving color combinations in hash values from the database through an API call and then saving them in localStorage for future use. However, I am facing a challenge when trying to access this data from localStorage and uti ...

Load prior state when the value changes with UseState in NextJS

In the development of my e-commerce application, I am currently working on implementing filters based on category and price for the Shop page. To handle this functionality, I have established the initial state as follows: const [filters, setFilters] = useS ...

Having trouble with CORS in your Angular application?

I am attempting to retrieve data from a site with the URL: Using the $http service After extensive research, I have come up with this CoffeeScript code snippet: angular.module('blackmoonApp') .controller 'PricingCtrl', ($scope, $ht ...

:Incorporating active hyperlinks through javascript

Hey there, I've encountered a little conundrum. I have a header.php file that contains all the header information - navigation and logo. It's super convenient because I can include this file on all my pages where needed, making editing a breeze. ...

Is there a workaround for utilizing a custom hook within the useEffect function?

I have a custom hook named Api that handles fetching data from my API and managing auth tokens. In my Main app, there are various ways the state variable "postId" can be updated. Whenever it changes, I want the Api to fetch new content for that specific p ...

Showing an in-depth ngFor post on the screen

I am in the process of building a Blog with Angular 7, MongoDB, and NodeJS. Currently, I have developed a component that iterates through all the posts stored in the database and showcases them on a single page. <div class="container-fluid"> < ...

Heroku's Node Express experiencing unexpected spikes in service response time

My Node application on Heroku is experiencing sporadic spikes in service times, sometimes reaching over 20000ms when it should be around 50ms. These spikes occur during static file loads and a simple API call that provides a heartbeat connection to active ...

Ensure that an async function's result is resolved before rendering react routes

I've been working on setting up an authentication service in my single-page application using React in the routes file. The goal is to check if a user is trying to access a private path, and verify that the token stored locally is valid. However, I&ap ...

Submitting both $_POST[] data and $_FILES[] in a single AJAX request

Struggling with uploading images along with dates on my website. I am passing the date using $_POST and the image files in $_FILES. Here is the Javascript code snippet: (function post_image_content() { var input = document.getElementById("images"), ...

Troubleshooting Vue v-for loop triggering click events on multiple items simultaneously

After conducting a thorough search, I haven't found a suitable answer for my issue. The problem I am facing involves a v-for loop with buttons on each item, using VueClipboard2 to copy text. Whenever a button is clicked, some CSS changes are applied t ...

Issues with AngularJS Directives not functioning properly when elements are added dynamically through an AJAX request

I am facing a scenario where I have a page featuring a modal window that is created using the AngularUI Bootstrap modal directive. The DOM structure for this modal is being dynamically loaded from the server, and it is triggered to open when a specific but ...

Step-by-step guide on incorporating Google Fonts and Material Icons into Vue 3 custom web components

While developing custom web components with Vue 3 for use in various web applications, I encountered an issue related to importing fonts and Google material icons due to the shadow-root. Currently, my workaround involves adding the stylesheet link tag to t ...

Boost Engagement with the jQuery PHP MySQL Like Feature

Seeking assistance in creating a like button with PHP, MySQL, and jQuery. I'm encountering an error but unable to pinpoint its source. Can anyone provide guidance? The project involves two pages: index.php & callback.php INDEX $k = 1; //POST ID $n ...

Transfer information through the react-native-ble-plx module

To initiate a project involving connected devices, I must establish a Bluetooth connection among the different devices. The objective is to develop an application using React Native and then transmit data from this application to my Raspberry Pi. The Rasp ...

Can you explain the purpose of the exec() method in this context?

When making a new user, I first check for duplicates using: const duplicate = await User.findOne({ username }).lean().exec(); I am puzzled by why the coding tutorial I am following includes the exec method. As far as I know, this method searches for a m ...

The Body Parser is having trouble reading information from the form

I'm struggling to understand where I'm going wrong in this situation. My issue revolves around rendering a form using a GET request and attempting to then parse the data into a POST request to display it as JSON. app.get('/search', (re ...

Choosing different elements using identical classes in JQuery

Struggling with a coding problem that seems like it should be an easy fix, but can't quite figure it out. The HTML code I have is as follows: <section class="actualite"> <div class="actualite-text"> <h3 class="title"&g ...

Create a styled-components component that renders a cross inside a recognizable object surrounded by borders

Currently developing an Object Recognition app and aiming to add a border around the object along with a cross that indicates the center. The border has been successfully implemented, but having trouble creating the cross. The plan is to add two more boxes ...