0

I am retriving data from a DB. I am using promise to return the data back to the client when the data is ready:

var http = require('http');
var mysql = require('mysql');


var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "******",
  database: "heroes"
});



let myPromise = new Promise(function(myResolve, myReject) {
    con.connect(function(err) {
      if (err) throw err;
      con.query("SELECT id, name FROM heroes", function (err, result, fields) {
        if (err) throw err;
        console.log(result);
        myResolve(JSON.stringify(result));
      });
    });
});




http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});

  myPromise.then(result => res.end(result))
   
    
  
}).listen(8080);

I have learned that you are supposed to supply two call-back functions to the Promise and that these are optional arguments in case of success or failure.

When I am calling myResolve() (which doesn't exist in this case), the data is being sent back to the client fine using .then(). Nonetheless, when I am not calling myResolve() something doesn't work and the page is being refreshed forever.

A. If these are indeed callbacks, how can I call a non exsiting function such as myResolve() ? Why I can't extract result without calling this function ?

B. How can I execute the database query only after there is a request on the 8080 port ? When I am trying to insert the promise into a function, I can't use .then (I am assuming the function by itself doesn't have any promise to give obiously).

Code Edit for the second question:

function connectToDB()
{
    let myResult;
    
    let myPromise = new Promise(function(myResolve, myReject) {
        con.connect(function(err) {
          if (err) throw err;
          con.query("SELECT id, name FROM heroes", function (err, result, fields) {
            if (err) throw err;
            console.log(result);
            myResolve(JSON.stringify(result));
            myResult = result;
          });
        });
    });
    
    return myResult;
}

Final code edit after wraping the promise with a function:

function connectToDB()
{

    
    let myPromise = new Promise(function(myResolve, myReject) {
        con.connect(function(err) {
          if (err) throw err;
          con.query("SELECT id, name FROM heroes", function (err, result, fields) {
            if (err) throw err;
            console.log(result);
            myResolve(JSON.stringify(result));

          });
        });
    });
    
    return myPromise;
}

Edit:

The questions are still valid, regardless of the use of res.send or res.end, as far as I understand it has got nothing to do with what I am asking about.

19
  • 2
    "When I am calling myResolve() (which doesn't exist in this case)" - what do you mean? Certainly the function exists, the promise constructor gave it to you. Commented Jul 8, 2021 at 21:13
  • Instead of if (err) throw err;, you should most definitely use if (err) myReject(err); else Commented Jul 8, 2021 at 21:14
  • "When I am trying to insert the promise into a function, I can't use .then" - yes you can. Please show us how you tried to use a function. The function should return the promise so that the caller can call the .then() method of the result. Commented Jul 8, 2021 at 21:15
  • @Bergi Maybe I am totaly off, but I am trying to understand. Isn't it a function name that I pass to the bigger function that I defined inside the promise in the constructor call ? Or do you mean that the constructor create this function using the name I supplied ("myResolve")? Commented Jul 8, 2021 at 21:16
  • @RT. Yes, the constructor does create this function, and passes it as an argument to the function you supplied. How you name the parameters of your function doesn't matter. Commented Jul 8, 2021 at 21:22

1 Answer 1

1

To answer these questions in order:

  1. The function 'myResolve' does exist, as it is being passed in when you create the promise: "new Promise(function(myResolve, myReject))". In this code, you are constructing a Promise object and passing a callback function into the constructor. The two parameters in this callback function are themselves callback functions which you are naming 'myResolve' and 'myReject'. Generally, people name them 'resolve' and 'reject', but the name does not matter as long as it is consistent throughout. Functions can be passed through functions just the same as strings and other types of variables.
  2. Right now, you are immediately declaring the 'myPromise' variable. You can defer the query until a request is hit by wrapping the 'myPromise' in a function which returns 'myPromise'. Then, when the request is made, call the new 'myPromiseFunction'.
Sign up to request clarification or add additional context in comments.

4 Comments

about 2, it works once but then I get : 'Error: Cannot enqueue Handshake after already enqueuing a Handshake'
It sounds like you might need to close the connection or reuse an existing connection after it has been created. I'm not too familiar with that library but that is what the error message sounds like.
Thanks I searched for the error and it seems like you don't need to call 'con.connect' if you already created a connection using 'createConnection': stackoverflow.com/questions/14087924/…
I need to note that it seems like the accepted answer in the link I provided is not correct for a long term use according to other comments there. So for other readers sake, be aware...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.