简体   繁体   中英

How to make a variable available to a callback function in javascript

In the following code, how do I make the variable songlist available to the callback function complete ?

If I run the code as is, sqlite successfully populates the songlist , but when the callback is run the variable becomes null .

Basically, I'm trying to figure out a way to ensure sqlite completes running before console.log(songlist) runs. I thought using a callback would do it, but then run into this variable passing issue. Thanks.

    var sqlite3 = require('sqlite3').verbose();
    var db = new sqlite3.Database('mydb.db');

    var songlist = []
    var complete = function (songlist) {
        console.log(songlist);
    }
    db.serialize(function () {
        db.each("SELECT rowid AS id, info FROM lorem where info like '%" + song + "%'", function (err, row) {
            songlist.push(row.info);
            console.log("each")
        }, complete)

    })

In your current code songlist is global, which means it's already available to your callback. When you add the songlist argument to the callback you are shadowing it which makes the global no longer visible.

You could simple say:

var complete = function () {
    console.log(songlist);
}

and log the global object.

But that's not very satisfying because you should generally avoid globals when not absolutely required.

A better idea is to define songlist in the function and pass it to your callback when you're done:

var complete = function (songlist) {
    console.log(songlist);
}
db.serialize(function () {
    var songlist = []

    db.each("SELECT rowid AS id, info FROM lorem where info like '%" + song + "%'", function (err, row) {
        songlist.push(row.info);
        console.log("each")
    }, function(){
          complete(songlist)
       }
    })
)}

Of course you don't really need a separate function — you could just log the songfest directly in the callback to your db function.

By creating an anonymous function that passes the songlist to complete as shown bellow:

var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('mydb.db');

var songlist = []
var complete = function (songlist) {
    console.log(songlist);
}
db.serialize(function () {
    db.each("SELECT rowid AS id, info FROM lorem where info like '%" + song + "%'", function (err, row) {
        songlist.push(row.info);
        console.log("each")
    }, function() { complete(songlist) })

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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