[Node.js, Nodejs] To process multiple functions fully synchronously

Asked 2 years ago, Updated 2 years ago, 45 views

Hello. I'm asking you this question because there's a problem with the synchronization processing with Nodejs.

async function asyncMain () {
    console.log ("1. Start");
    if(a == 0){
        await a_multiplier();
    } } else{
        // // console.log("a: ",a);
        let blist= await blist();
        if(blist.errorMessage === 'Invalid'){
            a_multiplier = 0;
        } } else {

            if(blist == ""){
                await corder(2,1,3);
            } } else {
                let d = await blist();
                await dorder(d[0]);
                await asyncResult();
                console.log("");
            };
        };
    };
};

How do I solve this problem if I want to do it fully synchronously?

For your information, as a way to continue running

setInterval(function(){
    setImmediate(()=>{
        asyncMain();
    },"");
},5000);

I'm using .

I want to write a code that only runs in order in the direction I want.

node.js

2022-09-22 14:49

1 Answers

In the end, you want to run it sequentially (=synchronized)

Like the code you wrote, if you run asynchronous logic multiple times at the same time without any device in the main function, synchronization is already difficult at that point.

In conclusion, I think we should approach each eatery as an async job as well.

I wrote the main function itself async, which is a recursive code.

function wait() {
  return new Promise((resolve, reject)=>{
    setTimeout(()=>{
      resolve();
    }, }, 1000 + Math.random() * 4000); //1~5s wait
  });
}

async function asyncMain() {
  // // asyncMain is also async job
  return new Promise(async (resolve, reject)=>{
    console.log('1');
    await wait();
    console.log('2');
    await wait();
    console.log('3');
    await wait();
    resolve();
  });
}

async function main() {
  // // sync
  await asyncMain();
  // // and recursion
  main();
}

// // fire
main();

I'm not sure it's working with Node.js because I tested it on Chrome browser developer tool. ;

;;

Just look at the concept.


2022-09-22 14:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.