0
\$\begingroup\$

I am a complete beginner in JavaScript / Node.js / Express, but have some experience with php.

I am trying to pass data from a SQLite database to the console. In my previous attempts, console.log() was executed before the database got queried. Now I got it to work in the correct order with what I think is a callback, and I'm getting the data in the console.

Questions:

-Is this an actual callback?

-Is there a better (shorter / easier) way to "do this after that"?

-If I want to execute multiple functions in a certain order, would I want to end up with something like doThis(doThat(thenDoThis(finallyDoThat)));?

-If there's anything else about the code, feel free to review and comment.

// Some test code to get data from database

function getAllChampions(callback){
    db.all("SELECT * FROM champions", function(error, rows){
        if (error) console.log(error);
        return callback(error, rows);
    });
};

function showAllChampions(error, champions){
    if (error) console.log(error);
    else console.log('Champions: ' + JSON.stringify(champions));
};

getAllChampions(showAllChampions);
\$\endgroup\$
2
\$\begingroup\$

If you run multiple async functions in a certain orderi it will look like something like this :

getData(function(a){  
    getMoreData(a, function(b){
        getMoreData(b, function(c){ 
            getMoreData(c, function(d){ 
                getMoreData(d, function(e){ 
                    ...
                });
            });
        });
    });
});

but it does not look nice and hard to control. Instead use promises, I recommend bluebirdjs library If you use nodejs, take it easy.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.