node.js - nodejs怎么同步从一个数据库查询函数中返回一个值?
ringa_lee
ringa_lee 2017-04-17 11:31:33
0
3
766

我想把从数据库中查询得到的值储存到一个变量中然后打印出来,但数据库查询是异步的,打印函数总是先一步调用,查询函数后一步调用,打印出来的值是空的。下面是代码。

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的异步回调真令人头痛啊,一直不知道怎么解决。

ringa_lee
ringa_lee

ringa_lee

reply all(3)
小葫芦

Congratulations on entering the callback pit

var sqlite3 = require('sqlite3').verbose();


var async = require('async');


var str = "";

var get_result = function(callback) {
    var db = new sqlite3.Database('score.db', function () {
        db.all("select * from score", function (err, res) {
            if (!err) {
                callback(JSON.stringify(res));
                console.log(str);//@1 这里输出的是有值的str
            }else {
                console.log(err);
            }
        });
    });
}

get_result(function(data){
    console.log(data)
})
巴扎黑

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.

  • There are some libraries that can make the code look more linear, such as async, promise, co. For details, see the appendix of the book above.
  • There are some database drivers that implement synchronous database queries, but this kind of library is basically impossible to use in a production environment because it will block other events.
Peter_Zhu

You can try this method:

var sqlite3 = require('sqlite3').verbose();

function selectFromDB(dbName, operation, callback) {
    var db = new sqlite3.Database(dbName, function () {
        db.all(operation, function (err, res) {
            if (!err) {
                str = JSON.stringify(res);
                return callback(null, str);
            } else {
                return callback(err);
            }
        });
    }); }

selectFromDB("score.db", "select * from score", function (err, result){
    if (err) {
        console.log(err);
    }
    else {
        console.log(result + "jjjj");
    } 
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template