Reputation: 423
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
Reputation: 214
To answer these questions in order:
Upvotes: 1