1

I'm new to Promise. This is my code

  function heavyProcess(){

    var ts = + new Date();
    while((+ new Date() - 2000) < ts ){
      //2 second delay to simulate lengthy process
    }
    console.log('after 2 seconds');

    return Promise.resolve("Done");
  }

  console.log("START");
  heavyProcess().then(function(resolve){
    console.log(resolve);
  });
  console.log("END");

It's output is

START
after 2 seconds
END
Done

How can I make it this way? I don't want a call to a heavy process blocks the next code.

START
END
after 2 seconds
Done

I've been reading about Promise but I seem can't make this work.

Heero Yuy
  • 614
  • 9
  • 24

1 Answers1

3

Is this what you need?

    var p = () => new Promise((resolve, reject) => {
setTimeout(() => {
console.log('after 2 seconds');
resolve("Done");
  }, 2000);
});

console.log("START");
p().then((data) => {
  console.log(data);
});
console.log("END");
Ghonima
  • 2,978
  • 2
  • 14
  • 23
  • yes, this code outputs my expected result but it's using setTimeout. I want to simulate a call to a lengthy process asynchronously without blocking execution of the next code – Heero Yuy Feb 25 '19 at 07:13
  • Then you should use web workers as @samsonthehero has said – Ghonima Feb 25 '19 at 08:55