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

Ways to display the page's content within a div container utilizing Jquery

I am attempting to display the content of a URL page (such as ) within a <div> using JQuery, but so far I have been unsuccessful. Here is an example of what I am trying to achieve: <div id="contUrl"> .. content of google.fr page </div> ...

Is there a clash with another code causing issues in troubleshooting a straightforward jQuery function?

jQuery(document).ready(function() { jQuery("#bfCaptchaEntry").on("click", function(){ jQuery("#bfCaptchaEntry").css("background-color", "#FFFFFF"); }); jQuery("#bfCaptchaEntry").on("blur", function(){ jQuery("#b ...

What is the best way to show my button only when within a specific component?

Is there a way to display the Logout button on the same line as the title only when the user has reached the Home component? In simpler terms, I don't want the logout button to be visible all the time, especially when the user is at the login screen. ...

What sets apart custom events from postMessage?

If you want to send a message to another document, such as an iframe, there are two functions you can use - postMessage and createEvent. Consider the following: var event = document.createEvent('CustomEvent'); event.initCustomEvent("message", tr ...

Managing the position of the caret within a content-editable div

I need help with editing a contenteditable div in HTML <div contenteditable="true" id="TextOnlyPage"></div> Here is my jQuery code: var rxp = new RegExp("(([0-9]+\.?[0-9]+)|([0-9]+))", "gm"); $('#TextOnlyPage').keyup(function( ...

Dragging a Google Maps marker causes a border to appear around a nearby marker

Recently, I added a main draggable marker to the map. However, an unusual issue arises when dragging this marker - a blue outline appears around one of the existing markers on the map. This behavior is puzzling as it seems to be triggered by a click event ...

The absence of a defined window - react-draft-wysiwyg integration with Next.js (SSR) is causing issues

Currently, I am in the process of developing a rich text editor that is used to convert plain HTML into editor content using Next.js for SSR. While working on this project, I encountered an error stating "window is not defined," prompting me to search for ...

Leveraging jQuery plugins within an AngularJs application

I am currently trying to implement the tinyColorPicker plugin from here in my Angular app, but I am facing difficulties with it. An error message keeps appearing: TypeError: element.colorPicker is not a function In my index.html file, I have included th ...

Why is my update with upsert: true not working in Express and Mongoose?

var logs = [{ mobilenumber: '1', ref: 3, points: 1000, ctype: 'mycredit', entry: 'sdfsdf', entry: 0 }, { mobilenumber: '1', ref: 6, points: 2000, ctype: 'mycredit', ...

Store data in Firebase Storage and retrieve the link to include it in Realtime Database

Utilizing Firebase Realtime Database and Firebase Storage for this application involves uploading images from the pictures array to Firebase Storage. The goal is to obtain the Firebase Storage link for each image, add it to the object pushed into imagesU ...

Utilize Bootstrap 3 Datepicker version 4 to easily set the date using Moment.js or Date objects

I'm currently utilizing the Within my project, I have a datetime picker labeled as dtpFrom <div class='input-group date ' id='dtpFrom'> <input type='text' class="form-control" /> <span c ...

Is it possible to transfer a value when navigating to the next component using this.props.history.push("/next Component")?

Is there a way I can pass the Task_id to the ShowRecommendation.js component? recommend = Task_id => { this.props.history.push("/ShowRecommendation"); }; Any suggestions on how to achieve this? ...

Update the content of the widget

Currently, I am utilizing the following script to display NBA standings: <script type="text/javascript" src="https://widgets.sports-reference.com/wg.fcgi?script=bbr_standings&amp;params=bbr_standings_conf:E,bbr_standings_css:1&amp"></sc ...

Language translation API specifically designed to convert text content excluding any HTML formatting

I have a dilemma with translating text content in an HTML file into multiple languages based on user input. To accomplish this, I am utilizing the Microsoft Translator AJAX interface. The structure of my HTML file looks something like this; <h1>< ...

A guide on how to automatically preselect a RadioGroup option in Material-UI

When a user selects an option from the MCQ Select using RadioGroup in my code and submits it, they should be able to return later and see the option they selected highlighted, similar to how Google Forms allows users to review their selections. Below is t ...

What is the best way to ascertain the variance between two Immutable.js Maps?

I currently have two unchangeable maps: const initial_map = Map({x: 10, y: 20)} const updated_map = Map({x: 15, y: 20)} Can anyone advise on how to find the changes between the two maps? The expected outcome should be: Map({x: 15}) ...

Storing text entered into a textarea using PHP

In a PHP page, I have a textarea and I want to save its content on click of a save button. The insert queries are in another PHP page. How can I save the content without refreshing the page? My initial thought was using Ajax, but I am unsure if it is saf ...

Search for text in multiple tables using jQuery and automatically trigger a button click event when the text is found

I am attempting to query certain tables and click a button within a cell of a specific table. Below is the code I am currently using: links[1].click(); iimPlayCode('WAIT SECONDS = 2') var compTabs = window.content.document.getElementById(' ...

How can I toggle button states within a v-for loop based on input changes in Vue.js?

Within the starting point of my code: https://plnkr.co/LdbVJCuy3oojfyOa2MS7 I am aiming to allow the 'Press' button to be active on each row when there is a change in the input field. To achieve this, I made an addition to the code with: :dis ...

Replace the hyphen with a comma using JavaScript

Looking for a way to modify a string like this: "PALS español K- add-on" by replacing the - with ,. The desired output should be: "PALS español K, add-on" Is there a JavaScript solution to achieve this task? ...