0

I made some DB operations and after some soap calls. Here is the result. It not seemed rigth to me. how can I synchronize them in nodejs? This all are async functions.

here is the code

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");
                    });
                });
            });
        });
    });
});
8
  • make sync the async,, you can't.. Once something is async everything up the chain has to be async too. But nodejs, does have async/await so can make this a lot easier. Commented Dec 8, 2021 at 10:52
  • I think you misunderstood my question. I did async functions already. Bu I want to make all of them work sync. Because when the first async function is resolved, it must start second async function, then it resolves, then third async function.. etc. Commented Dec 8, 2021 at 11:07
  • But this is exactly like asking, "Hi guys, I've built a race car, it's very efficient and wins all the races. Please tell me how I can sabotage it, make it heavier, clunky and inefficient, so it loses all the races. Because reasons. Thanks" Commented Dec 8, 2021 at 11:15
  • then you think this is the perferct version of my code? I did not see then->then->then->then usage before. and I'm brand new in nodejs :) Commented Dec 8, 2021 at 11:26
  • then->then->then->then Then you missed the bit about me saying there is async / await, that is the reason for it, It's not a direct replacement for sync coding, but syntax wise it makes it look pretty close.. eg, you will need to replace that forEach too, but it's nothing too drastic.. Commented Dec 8, 2021 at 11:48

1 Answer 1

0

"How to force something async to be sync" You probably can't anyway, and in the cases you can, you don't. EVER. As many questions, yours is an XY problem. You ask how to do something that you believe will solve your problem, when it will only make it worse.

You don't force an async process to be synchronous. You learn asynchronism and embrace its power, or you drop Node.js and use a synchronous language and runtime.

One of the ways to do it, and probably the most elegant, is to use await:

(Note : before someone comments "It needs to be in an async function", no it doesn't, since Node v14.8 which 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");

In a nutshell, everything written someFunction().then( result => can also be written const result = await someFunction(); It's syntactic sugar that looks like synchronous code but remains asynchronous.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Jeremy. here is my sccmConnectDB.js async function getAllComputers() { const cPool = new sql.ConnectionPool(sqlConfig); cPool.on('error', err => console.log('---> SQL Error: ', err)); try { await cPool.connect(); let result = await cPool.request().query(query); return result.recordsets; } catch (err) { return { error: err }; } finally { cPool.close(); } } module.exports = { getAllComputers: getAllComputers }
That forEach might also be better replaced with a for of.. Or your logging out before updating..
@Keith ooooooh... I didn't notice updateObject was async with a .then inside a .forEach... Let me fix that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.