我对nodejs很陌生,这可能就是为什么我问这个问题。我最近发现,使用nodejs对任何数据库进行的调用都是异步的。
作为一名前C#.Net程序员,这对我来说有点意外。我只是习惯于同步编码,所以可以稍等一下。
当前,我想进行数据库调用,并返回结果,代码应继续运行。如何做到最好?我发现了一些关于诺言的信息,但我找不到合适的解决方案。
我真正想要的是这样的东西:
var requestLoop = setInterval(function(){
console.log('Trading bot (re)started..');
var wlist = [];
wlist = db_connection.getWatchList_DB() ==> Database call here
if(wlist.length > 0){
// Perform the rest of the code
}
}, 5000);//300000 five minutes
所以,对我来说,可以等待数据库调用并继续获取结果。有没有简单的解决方案?
答案 0 :(得分:2)
您可以尝试使用此mysql2模块,该模块内置了对promises。官方代码片段的支持
async function main() {
// get the client
const mysql = require('mysql2');
// create the pool
const pool = mysql.createPool({host:'localhost', user: 'root', database: 'test'});
// now get a Promise wrapped instance of that pool
const promisePool = pool.promise();
// query database using promises
const [rows,fields] = await promisePool.query("SELECT 1");
}
如果您还不熟悉Node和异步编程,我建议您学习Callbacks
,Promises
以及课程Async-Await