简体   繁体   中英

NodeJS - Callback Not executed

After I execute a function (getAvailableLabs) in this case - I want to either execute a callback or a promise. I'm not sure which I should be executing however I can't get either to work.

Routes:

router.get('/api/content_left', function(req, res, next){
    const Labs = require("../models/Labs.js");

    l = new Labs("Sample Lab", "Sample Description", "Sample Category", "Sample Tech");

    l.getAvailableLabs(function(){
        console.log("We made it here!");
        });
    console.log("This is post resposnse");

Labs.js:

getAvailableLabs() {
    var d = db.any('select * from labs')
        .then(data => {
            console.log(data[0]);
            return data
        })
        .catch(function (error) {
            console.log(error + " - Error in function");
            return error;
    });
}

In the above case, it logs "end of available labs" followed by "this is post response". That's what I would expect with my understanding of callbacks. However it never executes "We made it here!" and I don't understand why? My impression is if I place a function within a function - it will be executed as a callback however this does not happen. Do I need return a specific way to execute a callback?

Thank you for your help.

Your getAvailableLabs function does not accept a callback parameter. I think it'd be best to stay consistent and use promises:

getAvailableLabs() {
    return db.any('select * from labs')
        .then(data => {
            console.log(data[0]);
            return data
        })
        .catch(function (error) {
            console.log(error + " - Error in function");
            return error;
    });
}

...

l.getAvailableLabs().then(data => {
    console.log("We made it here!");
});

If you'd like to use a callback instead of a promise here's how I'd write getAvailableLabs :

getAvailableLabs (callback) {
    db.any('select * from labs')
        .then(data => {
            console.log(data[0]);
            if (callback) { callback(null, data); }
        })
        .catch(function (error) {
            console.log(error + " - Error in function");
            if (callback) { callback(error); }
    });
}

Calling this function:

getAvailableLabs((err, data) => console.log("We made it here!");

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