RT.
RT.

Reputation: 423

Promises in JavaScript and NodeJS

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.

Upvotes: 0

Views: 220

Answers (1)

byte-this
byte-this

Reputation: 214

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'.

Upvotes: 1

Related Questions