Node.js数据库结果在函数内部返回较晚

时间:2019-01-25 14:38:39

标签: node.js

Node.js数据库结果在函数内部返回较晚

const db = req.app.db;

function getFeaturebyID(featureids) {
    db.planFeatures.findOne({"_id": featureids }).then(features => {
        return features.planFeaturesTitle;
    });
  }

const planLists ={};
db.planManagement.find({}).toArray((err, planList) => {

// res.end(JSON.stringify(planList));
featurearray = [];
    var j =1;
    planList.forEach(function(row) {
        planLists._id = row._id;
        features = row.planFeatures.split(',');

        for (let i = 0; i < features.length; i++) {
        featurearray[i] = getFeaturebyID(features[i]);
        // console.log(getFeaturebyID(features[i]));
        }
        //row.planFeaturesName[j] = featurearray;
        console.log(featurearray);
        j++;
      });
     //console.log(planList); 

//  res.end(JSON.stringify(req.session));

    res.render('stylist/plan_selection', {
        top_results: planList,
        title: 'Schedule',
        config: req.app.config,
        session: req.session,
        message: common.clearSessionValue(req.session, 'message'),
        messageType: common.clearSessionValue(req.session, 'messageType'),
        helpers: req.handlebars.helpers,
        showFooter: 'showFooter'
    });


});

});

返回features.planFeaturesTitle;在调用函数时晚返回一个值。我尝试回调但不起作用

1 个答案:

答案 0 :(得分:0)

这是由于node.js的异步特性造成的,

首先这样声明您的函数异步,

const getFeaturebyID = async (featureids) => {
    const features = await db.planFeatures.findOne({"_id": featureids });
    return features.planFeaturesTitle;
}

然后像这样使用它

planList.forEach(async (row) => {
    // your code here
    for (let i = 0; i < features.length; i++) {
        featurearray[i] = await getFeaturebyID(features[i]);
    }
    // your code here
});