依次执行NodeJS函数

时间:2019-05-31 22:15:34

标签: node.js asynchronous async-await

我在下面定义了一个函数库,因此可以动态调用它们。我在下面的模块中调用p10函数

module.exports = {
        p3: async function(mongo_db,data){
            mongo_db.collection('release', async function(err,coll){
                for(var i = 0; i <= data.searches.length-1; i++) {
                    var rlsId = data.searches[i].releaseId;
                    //console.log("RELEASE ID " + rlsId);
                    var tdcId = data.searches[i].tdcId;
                    if(rlsId !== null || rlsId !== undefined){
                        result = await  coll.findOne({"_id":ObjectId(rlsId)});
                        if(result){
                            //console.log("this is data searches for index " + i+ " " + JSON.stringify(data.searches[i]) 
                            //      + " and data.searches " + JSON.stringify(data.searches) + " and this is result " + JSON.stringify(result));
                            data.searches[i].releaseId = "release::" + result.initiativeId + "::" + result.name;
                            data.searches[i].tdcId = "testdachar::" +  tdcId;
                            var reservLst = data.searches[i].reservationIds;

                        }
                    }
                }
                return data
                //data_cb(data);
                //cb()
            })
            //return data
        },
        p8: async function(mongo_db, data){
            mongo_db.collection('reservation',async function(err,coll){
                for (var i =0 ; i< data.searches.length; i++){
                    var reservLst = data.searches[i].reservationIds;
                    for (var j=0; j<reservLst.length; j++){
                        var reservDoc = await  coll.findOne({"_id":ObjectId(reservLst[j])});
                        if(reservDoc){
                            data.searches[i].reservationIds[j] = "cardreserve::" + reservDoc.accountId; 
                        }
                    }
                }
                return data;
            })
        },
,
        p10: async function(mongo_db, data, data_cb){
            module.exports.p3(mongo_db,data).then(datax => {module.exports.p8(mongo_db,datax)}).then(data => {data_cb(data)}).catch(err => {console.log("ERROR " + err)});
        }

}

问题是我需要这些函数按顺序执行。我将它们分解为不同的功能。

我回来的错误是

  

(节点:17419)UnhandledPromiseRejectionWarning:TypeError:无法读取   未定义的属性“搜索”

就像p8函数不能对p3返回的数据进行操作一样,因为它似乎为空。我很困惑。请帮忙!

0 个答案:

没有答案