2017-11-30 14 views
1

js und jetzt ich bin vor ein Problem mit meinem app.js das Problem ist, ich möchte eine Funktion aufrufen, bevor die Route root ausgeführt wird die Funktion, die ich nennen möchte, ist wie folgt:mit Rückruf mit node.js

function findCats(){ 
    var cats; 
    Categorie.find({}, function(err, foundCats){ 
    if(err){ 
     console.log("Error can not find the categories ==> "+err); 
    }else{ 
     this.cats = foundCats; 
    } 
    }); 
    return this.cats; 
} 

es findet eine Kategorie aus einer Datenbank und das gibt das Ergebnis die Route root sendet dieses Ergebnis verwenden sollte, bevor ausführen res.render() diese Wurzel meiner Route ist

app.get("/",function(req, res){ 

      res.render("landing",{cats: findCats()}); 

}); 

dank ad Vance!

Antwort

0

einen Rückruf an Ihre findCats Funktion hinzufügen

function findCats(callback) { 
    var cats; 
    Categorie.find({}, function(err, foundCats){ 
    if (err) { 
     console.log("Error can not find the categories ==> " + err); 
    } else { 
     callback(foundCats); 
    } 
    }); 
} 

Ihre Antwort senden Dann Danke innerhalb dieser Rückruf

app.get("/",function(req, res){ 
    findCats((cats) => { 
     res.render("landing", {cats}); 
    }); 
}); 
+0

es funktionierte! –