依序执行2个异步功能以及相关输出

时间:2019-06-01 05:10:38

标签: node.js mongodb async-await async.js

我有一个功能模块:

module.exports = {
         p3: async function(mongo_db,data, cb){
            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;

                        }
                    }
                }
                if(err){
                    return cb(err)
                }
                return cb(null,data)
                //data_cb(data);
                //cb()
            })
            //return data
        },      p8: async function(mongo_db, data, cb){
            mongo_db.collection('reservation',async function(err,coll){
                for (var i =0 ; i< data.searches.length; i++){

                    if(data.searches[i].reservationIds){
                        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; 
                            }
                        }
                    }
                }
                if(err){
                    return cb(err);
                }
                return cb(null,data);
                //data_cb(data)
            })
        },

}

我试图依次执行p3和p8,因为其中一个的数据输出传递到了另一个。我正在尝试为此使用async.waterfall,但是在使用正确的语法时遇到了一些困难。你能帮忙吗?

1 个答案:

答案 0 :(得分:0)

由于进入回调地狱的机会非常低,因此可能很简单

p3(db, data, function(err, result){

    // do something with error or result


    p8(db, data, function(err, result){

        // do something with error or result

    });

});