How to inject data from multiple asynchronous calls into a pug template in Node?AngularJS : chaining http promises $q in a serviceHow to show data from mysql in nodejs with a refresh rateBasic Javascript promise implementation attemptECMAScript 6 Chaining PromisesBluebird promise resolve(data) is undefined in client codeConfuse about error and reject in PromiseUnhandled promise rejection in Node.jsMultiple rejects from promises in Promise.all, what exactly happens?can´t make your two or more methods in same routeNode JS Promise TypeError: Cannot read property 'then' of undefined

Can I ask the recruiters in my resume to put the reason why I am rejected?

How can saying a song's name be a copyright violation?

Twin primes whose sum is a cube

What's the point of deactivating Num Lock on login screens?

Will google still index a page if I use a $_SESSION variable?

How much of data wrangling is a data scientist's job?

I would say: "You are another teacher", but she is a woman and I am a man

In a spin, are both wings stalled?

1960's book about a plague that kills all white people

Could gravitational lensing be used to protect a spaceship from a laser?

Emailing HOD to enhance faculty application

Anagram holiday

Why "Having chlorophyll without photosynthesis is actually very dangerous" and "like living with a bomb"?

Why is it a bad idea to hire a hitman to eliminate most corrupt politicians?

Is it legal for company to use my work email to pretend I still work there?

Has there ever been an airliner design involving reducing generator load by installing solar panels?

Forgetting the musical notes while performing in concert

A reference to a well-known characterization of scattered compact spaces

Should I tell management that I intend to leave due to bad software development practices?

Why do I get two different answers for this counting problem?

Is it inappropriate for a student to attend their mentor's dissertation defense?

What mechanic is there to disable a threat instead of killing it?

Intersection of two sorted vectors in C++

Would Slavery Reparations be considered Bills of Attainder and hence Illegal?



How to inject data from multiple asynchronous calls into a pug template in Node?


AngularJS : chaining http promises $q in a serviceHow to show data from mysql in nodejs with a refresh rateBasic Javascript promise implementation attemptECMAScript 6 Chaining PromisesBluebird promise resolve(data) is undefined in client codeConfuse about error and reject in PromiseUnhandled promise rejection in Node.jsMultiple rejects from promises in Promise.all, what exactly happens?can´t make your two or more methods in same routeNode JS Promise TypeError: Cannot read property 'then' of undefined






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I'm new to Node and the concepts of promises, so I'm trying to wrap my head around the timing of when code will get called.



What I'm trying to do is to get a few different pieces of data from the database, then render it using pug.



If I had code like the following, when would the various bits of code get called, and would it achieve what I want it to achieve?



(apologies for any typos, this isn't compiled code)



function getData1(con) 
return new Promise(function (resolve, reject)
con.query('Select * from Table1', function(err, result)
if (err) reject(err);
else resolve(result);
)
)



function getData2(con)
return new Promise(function (resolve, reject)
con.query('Select * from Table2', function(err, result)
if (err) reject(err);
else resolve(result);
)
)


app.get('/', (req, res) => {

const mysql = require('mysql');
const con = mysql.createConnection(blah blah blah
);

con.connect((err) =>
if (err) throw err;
console.log('Connected!');
);

var data1;
var getData1 = getData1(con);
getData1.then(function(result)
data1 = result;
)

var data2;
var getData2 = getData2(con);
getData2.then(function(result)
data2 = result;
)

res.render('index', data1: data1,
data2 : data2);


I guess, more specifically, what I'm asking is:



1) Does getData1.then() and getData2() block, or do they behave like an event handler that gets called when the promise resolves?



2) Following on from that, Is res.render() only going to be called when we have values for data1, and data2, or does it need to be in the then() function?



3) If it needs to be in the then functions, what's a nice way to handle this given that I have two promises to wait for?



4) All the examples I saw for using the mysql module don't seem to use promises. Since getting a connection is asynchronous(?), isn't it possible that I'm trying to use the connection before I actually have it?



5) I'm from a java background so trying to think of this in terms of threads. Let's say both promises were rejected and I wanted to render the page with both errors, how would I go about building a list of error messages to be rendered? Is this like threads where both promises could reject at once and an attempt to build a list of errors is not safe? How would you go about making it thread safe?



thanks in advance for your comments!!










share|improve this question




























    0















    I'm new to Node and the concepts of promises, so I'm trying to wrap my head around the timing of when code will get called.



    What I'm trying to do is to get a few different pieces of data from the database, then render it using pug.



    If I had code like the following, when would the various bits of code get called, and would it achieve what I want it to achieve?



    (apologies for any typos, this isn't compiled code)



    function getData1(con) 
    return new Promise(function (resolve, reject)
    con.query('Select * from Table1', function(err, result)
    if (err) reject(err);
    else resolve(result);
    )
    )



    function getData2(con)
    return new Promise(function (resolve, reject)
    con.query('Select * from Table2', function(err, result)
    if (err) reject(err);
    else resolve(result);
    )
    )


    app.get('/', (req, res) => {

    const mysql = require('mysql');
    const con = mysql.createConnection(blah blah blah
    );

    con.connect((err) =>
    if (err) throw err;
    console.log('Connected!');
    );

    var data1;
    var getData1 = getData1(con);
    getData1.then(function(result)
    data1 = result;
    )

    var data2;
    var getData2 = getData2(con);
    getData2.then(function(result)
    data2 = result;
    )

    res.render('index', data1: data1,
    data2 : data2);


    I guess, more specifically, what I'm asking is:



    1) Does getData1.then() and getData2() block, or do they behave like an event handler that gets called when the promise resolves?



    2) Following on from that, Is res.render() only going to be called when we have values for data1, and data2, or does it need to be in the then() function?



    3) If it needs to be in the then functions, what's a nice way to handle this given that I have two promises to wait for?



    4) All the examples I saw for using the mysql module don't seem to use promises. Since getting a connection is asynchronous(?), isn't it possible that I'm trying to use the connection before I actually have it?



    5) I'm from a java background so trying to think of this in terms of threads. Let's say both promises were rejected and I wanted to render the page with both errors, how would I go about building a list of error messages to be rendered? Is this like threads where both promises could reject at once and an attempt to build a list of errors is not safe? How would you go about making it thread safe?



    thanks in advance for your comments!!










    share|improve this question
























      0












      0








      0








      I'm new to Node and the concepts of promises, so I'm trying to wrap my head around the timing of when code will get called.



      What I'm trying to do is to get a few different pieces of data from the database, then render it using pug.



      If I had code like the following, when would the various bits of code get called, and would it achieve what I want it to achieve?



      (apologies for any typos, this isn't compiled code)



      function getData1(con) 
      return new Promise(function (resolve, reject)
      con.query('Select * from Table1', function(err, result)
      if (err) reject(err);
      else resolve(result);
      )
      )



      function getData2(con)
      return new Promise(function (resolve, reject)
      con.query('Select * from Table2', function(err, result)
      if (err) reject(err);
      else resolve(result);
      )
      )


      app.get('/', (req, res) => {

      const mysql = require('mysql');
      const con = mysql.createConnection(blah blah blah
      );

      con.connect((err) =>
      if (err) throw err;
      console.log('Connected!');
      );

      var data1;
      var getData1 = getData1(con);
      getData1.then(function(result)
      data1 = result;
      )

      var data2;
      var getData2 = getData2(con);
      getData2.then(function(result)
      data2 = result;
      )

      res.render('index', data1: data1,
      data2 : data2);


      I guess, more specifically, what I'm asking is:



      1) Does getData1.then() and getData2() block, or do they behave like an event handler that gets called when the promise resolves?



      2) Following on from that, Is res.render() only going to be called when we have values for data1, and data2, or does it need to be in the then() function?



      3) If it needs to be in the then functions, what's a nice way to handle this given that I have two promises to wait for?



      4) All the examples I saw for using the mysql module don't seem to use promises. Since getting a connection is asynchronous(?), isn't it possible that I'm trying to use the connection before I actually have it?



      5) I'm from a java background so trying to think of this in terms of threads. Let's say both promises were rejected and I wanted to render the page with both errors, how would I go about building a list of error messages to be rendered? Is this like threads where both promises could reject at once and an attempt to build a list of errors is not safe? How would you go about making it thread safe?



      thanks in advance for your comments!!










      share|improve this question














      I'm new to Node and the concepts of promises, so I'm trying to wrap my head around the timing of when code will get called.



      What I'm trying to do is to get a few different pieces of data from the database, then render it using pug.



      If I had code like the following, when would the various bits of code get called, and would it achieve what I want it to achieve?



      (apologies for any typos, this isn't compiled code)



      function getData1(con) 
      return new Promise(function (resolve, reject)
      con.query('Select * from Table1', function(err, result)
      if (err) reject(err);
      else resolve(result);
      )
      )



      function getData2(con)
      return new Promise(function (resolve, reject)
      con.query('Select * from Table2', function(err, result)
      if (err) reject(err);
      else resolve(result);
      )
      )


      app.get('/', (req, res) => {

      const mysql = require('mysql');
      const con = mysql.createConnection(blah blah blah
      );

      con.connect((err) =>
      if (err) throw err;
      console.log('Connected!');
      );

      var data1;
      var getData1 = getData1(con);
      getData1.then(function(result)
      data1 = result;
      )

      var data2;
      var getData2 = getData2(con);
      getData2.then(function(result)
      data2 = result;
      )

      res.render('index', data1: data1,
      data2 : data2);


      I guess, more specifically, what I'm asking is:



      1) Does getData1.then() and getData2() block, or do they behave like an event handler that gets called when the promise resolves?



      2) Following on from that, Is res.render() only going to be called when we have values for data1, and data2, or does it need to be in the then() function?



      3) If it needs to be in the then functions, what's a nice way to handle this given that I have two promises to wait for?



      4) All the examples I saw for using the mysql module don't seem to use promises. Since getting a connection is asynchronous(?), isn't it possible that I'm trying to use the connection before I actually have it?



      5) I'm from a java background so trying to think of this in terms of threads. Let's say both promises were rejected and I wanted to render the page with both errors, how would I go about building a list of error messages to be rendered? Is this like threads where both promises could reject at once and an attempt to build a list of errors is not safe? How would you go about making it thread safe?



      thanks in advance for your comments!!







      mysql node.js promise






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 0:21









      Sportspunter.comSportspunter.com

      42




      42






















          0






          active

          oldest

          votes












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55054936%2fhow-to-inject-data-from-multiple-asynchronous-calls-into-a-pug-template-in-node%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55054936%2fhow-to-inject-data-from-multiple-asynchronous-calls-into-a-pug-template-in-node%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

          Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

          Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved