Connect guarantees while generating template

Fetching data through a function.

Establishing a connection and retrieving necessary information. Some code has been omitted for brevity.

function executeSQL(sql, bindParams , options) {
  return new Promise(function(resolve, reject) {
    ...
    resolve(result);
  });
}

Utilizing the function in a controller

exports.index = function(req, res){

    database.executeSQL('SELECT 1 FROM DUAL', [] , {})

    .then(function(result) {
      res.render('index' , { TITLE : 'Lorem Ipsum Blog' });
    })

    .catch(function(err) {
      next(err);
    });
};

The index controller is linked to the corresponding route.

I plan on invoking the executeSQL function twice. Only after both tasks are completed do I intend to call res.render to display the fetched data.

How should I sequence these calls? Is chaining them necessary or can I handle them asynchronously, waiting until both are finished before rendering?

Answer №1

Utilize the Promise.all method to handle multiple promises in JavaScript. When all of the promises in the iterable argument have resolved, Promise.all(iterable) returns a single promise that resolves.

function executeSQL(sql, bindParams, options) {
  return new Promise(function(resolve, reject) {
    resolve(result);
  });
}
exports.index = function(req, res) {
  var pro1 = database.executeSQL('SELECT 1 FROM DUAL', [], {});
  var pro2 = database.executeSQL('SELECT 1 FROM DUAL', [], {});
  Promise.all([pro1, pro2]).then(function(result) {
    console.log(result); //result will be an array
    res.render('index', {
      TITLE: 'Lorem Ipsum Blog'
    });
  }).catch(function(err) {
    next(err);
  });
};

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

What could be causing my externally hosted React component to malfunction when being imported via NPM?

After successfully creating a standalone component within my original project, I decided to explore the possibility of releasing it as an NPM module. To kick off this process, I attempted to load the library from another repository using NPM in a new proje ...

Obtain decrypted information from the token

I am facing difficulty in retrieving decrypted user data for the current user. Every time a user logs in, they receive a token. After logging in, I can take a photo and send it to the server. Looking at my code, you can see that this request requires a to ...

Is it better to manually input a list of select options in the user interface or retrieve them dynamically from the database in case of future changes?

Imagine designing a user interface that allows users to choose their favorite Pokemon from options like Bulbasaur, Squirtle, and Charmander. Within the database, there is a lookup table containing all possible choices: pokemon --- id name 1 Bulbasaur 2 ...

If an iframe contains a div with a particular class inside, then execute the following code

I need to dynamically add a class to the parent element if a specific class is present in its child. The issue: the content is within an iFrame and I'm not very proficient with jQuery. It doesn't necessarily have to be jQuery, any alternative m ...

What is the best way to display a date picker from a different page as a pop-up when a button is clicked on the current

Chapter One <button class="btn btn-outline-primary btn-sm btn-block " >Place order</button> Chapter Two <button class="simplepicker-btn" >Show Date Picker</button> > <script> > let simplepicker = new SimpleP ...

Building a secure NodeJS REST API with authentication capabilities utilizing Passport and OAuth2 with the integration of

Currently, I am in the process of developing a RESTful API using NodeJS and for authentication purposes, I have opted to utilize Passport. In order to maintain true RESTfulness, I have decided to implement token-based authentication instead of sessions. M ...

Encountering SCRIPT1014 and SCRIPT1002 errors within an Angular4 application when using Internet Explorer 11

My Angular 4 application runs perfectly in various browsers. However, when trying to launch it in Internet Explorer version 11, I encounter the following two errors: SCRIPT1014: Invalid character addScript.js (9,1) SCRIPT1002: Syntax error main.bundle.js ...

Expressjs makes it easy to upload audio files to your website

Currently, I'm developing a music app and I'm looking for the best way to upload an audio file in my ExpressJS application. Is it possible to use Cloudinary or is there another method that is more efficient? I attempted to follow the same proces ...

Uploading files with Ajax in PHP

Illustration of my Ajax script: Script <script type="text/javascript> $(document).ready(function(){ $('.costExcel').on("submit",function(event){ event.preventDefault() var url = "ajax.php"; ...

Optimize Material-UI input fields to occupy the entire toolbar

I'm having trouble getting the material-ui app bar example to work as I want. I've created a CodeSandbox example based on the Material-UI website. My Goal: My goal is to make the search field expand fully to the right side of the app bar, regar ...

Spin: twist beyond 360 degrees or less than 0 degrees

Attempting to rotate an arrow indicating wind direction using the transform: rotate() property. The data for rotation is retrieved from an API fetch, and conventional measurement of wind direction involves indicating where the wind is coming from. Therefo ...

Toastr - encountering a problem with the settings

After invoking a toastr message using the following command: Command: toastr["success"]("foo") toastr.options = { "closeButton": false, "debug": false, "newestOnTop": false, "progressBar": false, "positionClass": "toast-bottom-right", "prev ...

Is it common to have numerous operations in a single controller in AngularJS?

<!DOCTYPE html> <html ng-app="myApp" > <head> <title>myApp.html</title> </head> <body ng-controller="myCtrl as vm"> <br><br> <div> <p> I ...

The $http Service encounters a failure with an unknown status code

Difficulty Integrating AngularJS, jQuery, and Adobe Panel Creation I recently updated the versions of AngularJS and jQuery for my project. Previously, I was using jquery-1.11.0.min.js and AngularJS 1.2.10. Now, I want to utilize the latest available versi ...

Transfer a downloaded file from a secured pathway to the web browser

I have a setup with a react frontend and a nodejs/express backend. The backend has a protected route for serving files (downloads) like so: GET /api/file/:id When the frontend initiates a file download, it makes a request to this endpoint using the follo ...

Having trouble removing or adding a class to an HTML element?

I have a collection of three colored buttons. My goal is to allow users to select one button at a time, triggering it to be highlighted while the others are unselected. Each button corresponds to an object with a property called isSelected that can be set ...

What is the method for obtaining the dimensions of a shape drawn on Google Maps?

Is there a way to retrieve the dimensions of a shape drawn using the Google Maps API? I would like to obtain the measurements and include labels on top of the shape. Take a look at this image for reference The event argument in the overlay event does no ...

Transform a single attribute in an array of objects using angularjs and Javascript to a different value

Within an angularjs controller, the following code is used: var ysshControllers = angular.module('theControllers', []); ysshControllers.controller('CommonController', function($scope, $http, $route) { $scope.dbKey = $route ...

Error: React Component not rendering correctly - Element Type Invalid

React Uncaught Error: Element type is invalid Encountering a problem in my React application where the following error message appears: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite compone ...

How to efficiently store data using ajax and php techniques

I'm currently working on sending data via ajax for the user_question and language input fields. Can anyone help me with the correct way to include this element in the ajax JavaScript code so that I can save the table element value in my database? Tha ...