0

I am learning promises in Node JS. I came across a certain code which I want to synchronize it (Out of Curiousity).

function test1(){
  return new Promise(async function(resolve,reject){
      await promise1();
      await promise2();
      await promise3();
      console.log('last');
      resolve(true);
  })

}

async function promise1(){
  return new Promise(async function(resolve,reject){
      console.log('promise1');
      await setTimeout(myFunc, 1500, resolve);
      console.log("111");
  });
}

function myFunc(resolve) {
  console.log(`arg was => resolve`);
  resolve(true);
}

function promise2(){
  return new Promise(function(resolve,reject){
      console.log('promise2');
      resolve(true);
  });
}

function promise3(){
  return new Promise(function(resolve,reject){
      console.log('promise3');
      resolve(true);
  });
}

function callTest1(){
  for(i=0;i<4;i++){
    test1();
  }
}

callTest1();

I want the output like this :

promise1
arg was => resolve
111
promise2
promise3
last
promise1
arg was => resolve
111
promise2
promise3
last
promise1
arg was => resolve
111
promise2
promise3
last
promise1
arg was => resolve
111
promise2
promise3
last

I want my code to wait for setTimeOut and then after only it should run other function. I know, in node js we have concept of Asynchronization But somehow I want this code to be sync.

  • 1
    https://stackoverflow.com/q/6048504/1531971 –  Dec 17 '18 at 15:52
  • Possible duplicate of [Synchronous request in Node.js](https://stackoverflow.com/questions/6048504/synchronous-request-in-node-js) – dr0i Dec 17 '18 at 16:16
  • Never ever pass an `async function` as a callback to `new Promise`! – Bergi Dec 17 '18 at 18:38

1 Answers1

0

A key rule in node.js is that it is impossible to synchronize asynchronous code.

You can easily obtain your desired result by making callTest itself asynchronous, for example:

async function callTest1() {
  for(i=0;i<4;i++){
    await test1();
  }
}

Now your output will appear as desired, but of course the call to callTest1() will return immediately (and the output will print afterwards).

Elliot Nelson
  • 11,371
  • 3
  • 30
  • 44