Reputation: 1
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");
});
});
});
});
});
});
Upvotes: 0
Views: 3704
Reputation: 26400
"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.
Upvotes: 0