简体   繁体   English

node.js mySQL获取记录

[英]node.js mySQL get record

Coming from a strong PHP/MySQL and Python/MySQL background, I can't seem to wrap my head around the asynchronous nature of javascript/node.js, so I've started exploring 'promises.' 来自强大的PHP / MySQL和Python / MySQL背景,我似乎无法绕过javascript / node.js的异步性质,所以我开始探索'promises'。 I have a sort-of implementation, but in the output, the best I can get get is [object Promise] as a result... 我有一种实现,但在输出中,我能得到的最好的是[对象Promise]因此......

How do I convert the [object promise] to an array or a value that I can render on the page? 如何将[对象承诺]转换为我可以在页面上呈现的数组或值?

index.html: index.html的:

<button type="button" onclick="get_row();">
  Get Row
</button>
<div id="output"></div>
<script src="./js/app.js"></script>

app.js: app.js:

var db = require('./js/db.js');

function get_row() {
  var result = db.dosql('SELECT * from table LIMIT 1')
  result.then(
     document.getElementById("output").innerHTML = result;
  )
};

db.js: db.js:

var mysql       = require('mysql');
var credentials = {
  host     : 'localhost',
  user     : 'user',
  password : 'pass',
  database : 'schema'
};


function dosql(sql) {
  return new Promise((resolve, reject) => {
    var connection = mysql.createConnection(credentials);
    connection.connect();
    connection.query(sql, (err, result) => {
      if (!err){
        return resolve(result)
      }else{
        return reject(err)
      }
    });
    connection.end();
  })
}

exports.dosql = dosql;

Footnote: I'm reasonably certain I have no idea what I'm doing here -- and accept that any of this code could be a complete bastardization of javascript and promises. 脚注:我有理由相信我不知道我在这里做了什么 - 并且接受这些代码中的任何一个都可能是javascript和promises的完全混蛋。

UPDATE: 更新:

I stumbled into rewriting app.js like so: 我偶然发现了重写app.js:

function get_row() {
  var result = db.dosql('SELECT * from table LIMIT 1')
  result.then(function(value){
    document.getElementById("output").innerHTML = value[0].row;
  })
};

Which does indeed output the expected value for row. 哪个确实输出了行的预期值。 Which works... but I'm not sure why... 哪个有效...但我不确定为什么......

Once I was lost, now I'm found (callback has to 'do something' with the value via a function): 一旦我迷路了,现在我找到了(回调必须通过一个函数'做一些事情'):

app.js: app.js:

function get_row() {
  var result = db.dosql('SELECT * from table LIMIT 1')
  result.then(function(value){
    document.getElementById("output").innerHTML = value[0].row;
  })
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM