一次等待一个查询

时间:2019-05-02 00:38:51

标签: javascript node.js sql-server asynchronous async-await

因此,我正在尝试使用nodejs和mssql将顺序链插入到数据库中。快速概述如下:

  1. 在条件表中插入
  2. 插入任务表

以此类推。

这是我的代码:

    var PODKEY = process.env.PODKEY;
var ADDBY = process.env.ADDBY;
var dateTimeNow = new Date(Date.now()).toISOString().replace(/Z$/, "");

(async function () {
    try {
        DecryptConnectionString(connectionString, 'ProductIpsMasterConnectionString')
            .then(async function () {
                let connectionConfigurationObject = await BuildConnectionConfigurationObject(connectionString);
                await sql.connect(connectionConfigurationObject).then(async function () {
                    GetTenantsInfoByPodKey(PODKEY).then(async function (resultTenantsInfo) {
                        resultTenantsInfo.forEach(async function (tenant) {
                            var transaction = new sql.Transaction();
                            await transaction.begin(async function () {

                                let tenantConnectionConfigurationObject = await BuildConnectionConfigurationObject(tenant.CONNECTIONSTRING);

                                await sql.connect(tenantConnectionConfigurationObject).then(async function () {
                                    console.dir("Connected to Tenant ID: " + tenant.TENANTID);
                                    await InsertCondition(transaction).then(async function (resultCondition) {
                                        console.log("Successfully Inserted, Condition Key: " + resultCondition[0].conditionKey);
                                        await InsertTask(transaction, resultCondition[0].conditionKey).then(async function (resultTask) {
                                            console.log("Successfully Inserted, TaskKey: " + resultTask[0].taskKey);
                                            transaction.commit();
                                        });

                                    }).catch(function (err) {
                                        console.error("Error Inserting Condition: " + err);
                                    });
                                }).catch(function (err) {
                                    console.error("Error connecting to Tenant DB: " + err);
                                });

                            });
                        });
                    }).catch(function (err) {
                        console.error("Error getting Tenants Info: " + err);
                    });
                }).catch(function (err) {
                    console.log('error connecting to Master DB:' + err);
                });
                console.dir("Connected Successfully to Master DB!");
            }).catch(function (err) {
                console.log('error decrypting connection string :' + err);
            });

    } catch (err) {
        console.error("Error Occured: " + err);
    }
})()

function GetTenantsInfoByPodKey(transaction, podKey) {
    return new Promise(function (resolve, reject) {
    new sql.Request(transaction).query(query).then(function (recordset) {
        resolve(recordset)});
    });
}

function InsertCondition(connectionObject, transaction) {
    return new Promise(function (resolve, reject) {
       var query = "insert into table(col1,col2..) values (val1,val2,..);select SCOPE_IDENTITY() AS conditionKey;"
       new sql.Request()
               .query(query, (err, recordset) => {
                resolve(recordset);
                });
     });
}

 function InsertTask(connectionObject, transaction) {
    return new Promise(function (resolve, reject) {
       var query = "insert into table(col1,col2..) values 
   (val1,val2,..);select SCOPE_IDENTITY() AS taskKey;"
       new sql.Request()
               .query(query, (err, recordset) => {
                resolve(recordset);
                });
     });
}

假设查询工作正常并且可以插入,但是即使我使for()循环无法完成sql.connect并在内部方法“ InsertCondition”中也遇到了问题,但forEach却碰到了它,但看起来像那样它将跳过整个sql.connect块并继续进行下一个迭代。

问题: 1.)我怎样才能使GetTenantsInfoByPodKey(),sql.connect和InsertCondition()正确地处于等待状态?等待这些方法中的每一个先完成,然后再进行下一个操作? [已解决]

2。)当我手动查询数据库时,它没有反映在数据库中,但是它返回从SCOPE_IDENTITY()插入的密钥 Insert and committ 如何确保插入?像它先提交InsertCondition(),然后提交InsertTask()内的下一个方法

这是我正在尝试的完整应用程序: https://jsfiddle.net/25serz3c/1/

谢谢

1 个答案:

答案 0 :(得分:1)

async function f () {

    for(const tenant of resultTenantsInfo) {
      const connectionObjTenant = BuildConnectionConfigurationObject(tenant.CONNECTIONSTRING);
      await sql.connect(connectionObjTenant);
      const transaction = new sql.Transaction();
      awai transaction.begin()
      const resultCondition = await InsertCondition(transaction)
      console.log("Inserting Condition was successfull. Condition Key: " + resultCondition[0].conditionKey);
      await transaction.commit();
      console.dir("Transaction commited.");
    }
}

f()