【问题标题】:How to make sync the async functions in node js如何在节点 js 中同步异步函数
【发布时间】:2021-12-08 20:50:26
【问题描述】:

我做了一些数据库操作和一些肥皂电话。这是结果。这对我来说似乎不正确。如何在 nodejs 中同步它们?这都是异步函数。

这里是代码

sccmConnectDB.getAllComputers().then(result => {
    computers = result[0]
    console.log("select from sccm db is completed...")
    caConnectDB.deletezSCCM2CM().then(result => {
        console.log("deleting from ca db zsccm2cm table is completed...");
        caConnectDB.insertzSCCM2CM(computers).then(result => {
            console.log("inserting ca db zsccm2cm table is completed...");
            login.login().then(sessionId => {
                console.log("login successfull");
                getHostName.getHostNames().then(result => {
                    hostNames = result[0]; 
                    console.log("query result for hostname -->", hostNames);
                    hostNames.forEach(element => {
                        uuid = "nr:" + element.uuid;
                        attrVals = { string: ["system_name", element.compName] };
                        attrbts = { Attributes: [] }
                        updateObject.updateObject(sessionId, uuid, attrVals, attrbts).then(result => {
                            console.log("Update successfull");
                        });
                    });
                    logout.logout(sessionId).then(result => {
                        console.log("logout successfull");
                    });
                });
            });
        });
    });
});

【问题讨论】:

  • make sync the async,,你不能......一旦某件事是异步的,链上的所有东西也必须是异步的。但是 nodejs 确实有 async/await,所以可以让这变得更容易。
  • 我想你误解了我的问题。我已经做了异步功能。但我想让它们都同步工作。因为当第一个异步函数被解析时,它必须启动第二个异步函数,然后解析,然后是第三个异步函数..等等。
  • 但这就像在问,“大家好,我已经制造了一辆赛车,它非常高效并且赢得了所有比赛。请告诉我如何破坏它,让它变得更重、更笨重而且效率低下,所以它输掉了所有的比赛。因为原因。谢谢”
  • 那么你认为这是我的代码的完美版本吗?我之前没有看到 then->then->then->then 的用法。我是 nodejs 的新手 :)
  • then->then->then->then 然后你错过了关于我说有async / await 的那一点,这就是它的原因,它不是同步编码的直接替代品,但在语法方面它使它看起来非常接近.. 例如,您也需要替换那个 forEach,但这并不太激烈..

标签: javascript node.js asynchronous promise synchronization


【解决方案1】:

“如何强制异步同步”你可能无论如何都不能,在你可以的情况下,你不能。曾经。很多问题,你的问题是XY problem。你问如何做一些你相信会解决你的问题的事情,但它只会让事情变得更糟。

您不会强制异步进程同步。你学习异步并接受它的力量,或者你放弃 Node.js 并使用同步语言和运行时。

使用await

(注意:在有人遇到“它需要在异步函数中”之前,不,它没有,因为 Node v14.8 supports top-level await

let result = await sccmConnectDB.getAllComputers();
const computers = result[0];
console.log("select from sccm db is completed...")
await caConnectDB.deletezSCCM2CM();
console.log("deleting from ca db zsccm2cm table is completed...");
await caConnectDB.insertzSCCM2CM(computers);
const sessionId = await login.login();
console.log("login successfull");
result = await getHostName.getHostNames();
const hostNames = result[0];
console.log("query result for hostname -->", hostNames);

let uuid, attrVals, attrbts;

for (let element of hostNames) {

  uuid = "nr:" + element.uuid;
  attrVals = { string: ["system_name", element.compName] };
  attrbts = { Attributes: [] };

  await updateObject.updateObject(sessionId, uuid, attrVals, attrbts);
  console.log("Update successfull");
}

await logout.logout(sessionId);
console.log("logout successfull");

简而言之,所有写成someFunction().then( result => 的东西也可以写成const result = await someFunction(); 它是语法糖,看起来像同步代码,但仍然是异步的。

【讨论】:

  • 谢谢杰里米。这是我的 sccmConnectDB.js 异步函数 getAllComputers() { const cPool = new sql.ConnectionPool(sqlConfig); cPool.on('error', err => console.log('---> SQL Error: ', err));尝试 { 等待 cPool.connect();让结果 = 等待 cPool.request().query(query);返回结果。记录集; } 捕捉(错误){ 返回 { 错误:错误 }; } 最后 { cPool.close(); } } module.exports = { getAllComputers: getAllComputers }
  • forEach 也可以更好地替换为 for of.. 或者您在更新之前注销..
  • @Keith oooooooh...我没有注意到 updateObject.then 中的 .then 异步...让我解决这个问题
猜你喜欢
  • 2018-01-11
  • 1970-01-01
  • 1970-01-01
  • 2020-07-16
  • 1970-01-01
  • 2019-12-23
  • 2020-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多