I'm currently working on a brackets text-editor extension that keeps your work time in a database and lets you view your time entries. I'm using NodeJS to interact with the SQL server. I've been able to enter time as I want and I've successfully called the entries with a select statement. However, I am trying to display the results on a panel at the bottom of brackets.
I can't figure out how to get the result from my select statement to the wider scope so I can pass it to main.js. I'm new to Node and have read a lot about callbacks and promises but nothing seems to help. I tried using a callback but I can't get the value from the callback to equal a variable that can be returned.
UPDATE: The viewTime() function is returned to main.js as a promise. If I could name con.connect() as a regular function then I could call it in main.js through registerCommand (command handler function).
Here's the code:`
(function () {
"use strict";
var mysql = require('mysql');
/**
* @private
*
* @return {array}
*/
function viewTime() {
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "brackets_timer_data"
});
con.connect(function(err) {
if (err) {
console.log(err);
} else {
console.log("Connected!");
}
con.query("SELECT * FROM work_sessions", function (err, result, fields) {
if (err) {
console.log(err);
}
//I need to get the result from here
});
});
//And return it here so I can pass the variable to main.js
}
/**
* Initializes the test domain with several test commands.
* @param {DomainManager} domainManager The DomainManager for the server
*/
function init(domainManager) {
if (!domainManager.hasDomain("view")) {
domainManager.registerDomain("view", {major: 0, minor: 1});
}
domainManager.registerCommand(
"view", // domain name
"viewTime", // command name
viewTime, // command handler function
false, // this command is synchronous in Node
"Returns time entry results.",
[{}],
[{name: "results", // return values
type: "array",
description: "Time entry results"}]
);
}
exports.init = init;
}());
`Any thoughts?