异步数据调用后,Javascript处理页面重定向

时间:2017-12-31 23:21:08

标签: javascript node.js ejs

我正在使用Node和express和ejs来测试一个简单的苹果。我有以下代码段,由我的结果页面的路由调用触发。我想要的是从我的mongodb集合中获取所有结果后重定向到结果页面。一切正常,在我的db文件中的GetResults函数的console.log中,函数正在检索并返回结果。我想我正在处理我对DBHandler的异步性质,但我怎样才能做到这一点?

router.get("/results",isLoggedIn, function(req,res){
     var results = DBhandler.GetResults(req,res);

     console.log("value of results right before it is passed to results.ejs:  ", results)

     ////COME BACK AND MAKE THIS A PROMISE TO RUN AFTER THE RESULTS IS FETCHED
     res.render("results.ejs", {results:results});
 });

我的数据库功能

exports.GetResults = function (req, res) {

    console.log(req.body);

    //get all the results
    ResultModel.find({},function(err, result){
        if(err){
            console.log("SOMETHING WENT WRONG GETTING RESULTS: ", err)
        }else{
            console.log("this is the value of result from the getresults call: ", result);
            return result;
        }
    });
}

1 个答案:

答案 0 :(得分:1)

如果DBHandler返回一个你可以使用的承诺

router.get("/results",isLoggedIn, async function(req,res){
 var results = await DBhandler.GetResults(req,res);

 console.log("this is the value of results right before it is passed to results.ejs:  ", results)

 ////COME BACK AND MAKE THIS A PROMISE TO RUN AFTER THE RESULTS IS FETCHED
 res.render("results.ejs", {results:results});
});

如果它返回回调

router.get("/results",isLoggedIn, function(req,res){
   DBhandler.GetResults(req,res, function(err, results){
        console.log("this is the value of results right before it is passed to results.ejs:  ", results)

        res.render("results.ejs", {results:results}); 
   })
 });