我想把从数据库中查询得到的值储存到一个变量中然后打印出来,但数据库查询是异步的,打印函数总是先一步调用,查询函数后一步调用,打印出来的值是空的。下面是代码。
var sqlite3 = require('sqlite3').verbose();
var async = require('async');
var str = "";
var db = new sqlite3.Database('score.db', function () {
db.all("select * from score", function (err, res) {
if (!err) {
// console.log(JSON.stringify(res));
str = JSON.stringify(res);
console.log(str);//@1 这里输出的是有值的str
}else {
console.log(err);
}
});
});
console.log(str+"jjjj");//@2 这里输出的Str,是没有值的空的
下面是输出结果:
jjjj 这是@2console打印的,Str是空的
[{"id":1,"name":"jim","score":"100"},{"id":2,"name":"tom","score":"200"}]
这是@1 console打印的,str是有值的。
请问怎样让查询回调先执行,让str获得值,传递出来,然后再执行最后一句@2的打印语句。javascript的异步回调真令人头痛啊,一直不知道怎么解决。
Congratulations on entering the callback pit
In your example, you can only put the sentence that prints the results into the callback function. In short, you don’t want the code to execute linearly in Node.js.
Recommend a book about JavaScript asynchronous process control: JavaScript Asynchronous Programming.
You can try this method: