异步函数在使用promises的循环内部按顺序运行

时间:2018-02-02 13:02:24

标签: javascript mongodb

我有一个在需要插入mongodb数据库的for循环数据中运行的方法。

在插入之前我需要查询数据库以查看是否存在类似的记录,以便我可以给它相同的代码,我需要找到记录的最大代码并给插入的方法下一个最高的代码

我需要的输出是Code,0,2,插入第一个记录然后Code,1,2,insert但我收到的输出是代码,0代码,0代码,0代码,0 2,2,2 ,2告诉我每个动作在循环中一个接一个地运行,而不是按照我需要的顺序运行

//First Promise
                    const BatchCheckPromise = new Promise((resolve) => {
                        const Code = "";

                        var query = {
                            BatchCode: {
                                $eq: Row.BatchCode
                            }
                        }

                        //Mongo Database Query To Get Code From The Batch
                        var BatchRow = db.collection("ap_transaction_line").find(query).toArray();

                        BatchRow.then(function(db_data){
                            console.log("Code");
                            console.log(db_data.length);
                            //Get code if in database
                            if (db_data.length > 0) {
                                Code = db_data[0].Code;
                            }
                            resolve(Code)
                        });
                    });

                    //Second Promise
                    async function MaxCheckPromise(Code) {
                        return new Promise(
                            (resolve, reject) => {
                                //If code is still null after checking the database
                                if (Code == "" || Code == null) {
                                    var Code = "";

                                    var query = {
                                        Prefix: {
                                            $eq: Row.Prefix
                                        }
                                    }

                                    var sort = {
                                        Code: -1
                                    };

                                    //Mongo Database query for max code in the database
                                    var MaxRow = db.collection("ap_transaction_line").find(query).sort(sort).limit(1).toArray();

                                    MaxRow.then(function(db_data){
                                        Code = db_data[0].Code;
                                        Code++;
                                        //Increment by 1 for new code
                                        resolve(Code);
                                        /////////
                                    });                                        
                                }
                                else {
                                    resolve(Code);
                                }
                            }
                        )
                    }

                    //Insert function
                    async function InsertInToDataBase() {
                        try {          
                            //first promise to query the batchcode              
                            let BatchCode = await BatchCheckPromise;

                            //second promise to query the max code if no batchcode
                            let MaxCode = await MaxCheckPromise(BatchCode);

                            console.log(MaxCode);

                            //Insert into Database with new Code
                            if (Row.TimeStamp == "U") {
                                //vars
                                //db query
                                var db_collection = "ap_transaction_line";
                                var db_query = {
                                    LocalID: Row.LocalID
                                };
                                var db_data = {
                                    TimeStamp: Row.TimeStamp,
                                    Error: Row.Error,
                                    SyncID: Row.SyncID,
                                    DateCreated: Row.DateCreated,
                                    BatchCode: Row.BatchCode,
                                    TransCode: Row.TransCode,
                                    ConsCode: Row.ConsCode,
                                    DebitCode: Row.DebitCode,
                                    Prefix: Row.Prefix,
                                    Code: MaxCode,
                                    ToAcc: Row.ToAcc,
                                    FromAcc: Row.FromAcc,
                                    Vendor_Client: Row.Vendor_Client,
                                    Date: Row.Date,
                                    Description: Row.Description,
                                    Qty_Calls: Row.Qty_Calls,
                                    Price_Rate: Row.Price_Rate,
                                    TotalEX: Row.TotalEX,
                                    Ref: Row.Ref,
                                    Detail: Row.Detail,
                                    Username: Row.Username,
                                    PaidStatus: Row.PaidStatus,
                                    Period: Row.Period,
                                    PeriodAuth: Row.PeriodAuth,
                                    BankRecon: Row.BankRecon,
                                    PDFName: Row.PDFName,
                                    Auth: Row.Auth,
                                    InvItem: Row.InvItem,
                                    InvPicName: Row.InvPicName,
                                    EpsNum: Row.EpsNum,
                                    BatchGroup: Row.BatchGroup
                                };
                                m_connect("updateOne", DbName.DBname, db_collection, db_query, "", db_data, "", function (db_connect) {
                                    //console.log('db_connect');
                                    //console.log(db_connect);

                                });
                            } else if (Row.TimeStamp == "") {
                                //db query
                                var db_collection = "ap_transaction_line";
                                var db_query = {
                                    SyncID: Row.SyncID
                                };
                                var db_data = {
                                    TimeStamp: Row.TimeStamp,
                                    Error: Row.Error,
                                    SyncID: Row.SyncID,
                                    DateCreated: Row.DateCreated,
                                    BatchCode: Row.BatchCode,
                                    TransCode: Row.TransCode,
                                    ConsCode: Row.ConsCode,
                                    DebitCode: Row.DebitCode,
                                    Prefix: Row.Prefix,
                                    Code: MaxCode,
                                    ToAcc: Row.ToAcc,
                                    FromAcc: Row.FromAcc,
                                    Vendor_Client: Row.Vendor_Client,
                                    Date: Row.Date,
                                    Description: Row.Description,
                                    Qty_Calls: Row.Qty_Calls,
                                    Price_Rate: Row.Price_Rate,
                                    TotalEX: Row.TotalEX,
                                    Ref: Row.Ref,
                                    Detail: Row.Detail,
                                    Username: Row.Username,
                                    PaidStatus: Row.PaidStatus,
                                    Period: Row.Period,
                                    PeriodAuth: Row.PeriodAuth,
                                    BankRecon: Row.BankRecon,
                                    PDFName: Row.PDFName,
                                    Auth: Row.Auth,
                                    InvItem: Row.InvItem,
                                    InvPicName: Row.InvPicName,
                                    EpsNum: Row.EpsNum,
                                    BatchGroup: Row.BatchGroup
                                };
                                //m_connect("queryAll", db_collection, "", "", function(db_connect){

                                m_connect("insertone", DbName.DBname, db_collection, db_query, "", db_data, "", function (db_connect) {
                                    //console.log('db_connect');
                                    //console.log(db_connect);
                                    console.log("Insert");

                                });
                            }
                        }
                        catch (error) {
                            console.log(error.message);
                        }
                    }

                    //Run the functions async
                    (async () => {
                        await InsertInToDataBase();
                    })();

1 个答案:

答案 0 :(得分:0)

我建议你依靠像Axios这样的库来管理带有promises的ajax调用,因为它增加了很好的功能,比如串行调用(你需要的那个)和并行调用。