Search code examples
javascriptasynchronoussettimeoutasynccallback

what's the point of wrapping promise into setTimer() and not?


promise with no setTimeout()

console.log('Prmoise start');
const lotteryPromise = new Promise(function (resolve, reject) {
   if(Math.random() >= 0.5) {
      resolve('You won the lottery');
   } else {
      reject(new Error('You lost your money'));
   }
});
 
lotteryPromise.then(res => console.log(res)).catch(err => console.error(err));
console.log('Promise end');

promise with setTimeout()

    console.log('Prmoise start');
    const lotteryPromise = new Promise(function (resolve, reject) {
    setTimeout( () => {
       if(Math.random() >= 0.5) {
          resolve('You won the lottery');
       } else {
          reject(new Error('You lost your money'));
       }
       },2000);
    });
     
    lotteryPromise.then(res => console.log(res)).catch(err => console.error(err));
    console.log('Promise end');

I don't understand the usage of setTimeout() wrap in promise? Even without the setTimeout() wapping the promise is gettitng executing asynchronously right i.e it is added to eventQueue ? Is that SetTimeout is just delaying the code execution or Is there anything else I am missing? By the way I know how call stack, micro tasks and callback queue works....


Solution

  • You're addressing this problem backwards. You should be asking: What is the point of using a promise without setTimeout?

    The purpose of a promise is to manage asynchronous code in a standard way.

    The purpose of the new Promise constructor is to create a promise for asynchronous code which doesn't use promises natively.


    In your first chunk of code, there is nothing asynchronous about the function you pass to Promise(). It's a pointless promise.

    In your second chunk of code, the setTimeout is asynchronous but you've no way to know when it is finished (other than modifying the callback you pass to it). Using new Promise with it allows you to use the promise object to do something when the setTimeout is complete.

    That said, there's no obvious reason to use setTimeout or promises at all for this example. It's entirely contrived to demonstrate how promises work, not to be a practical example of when you should use a promise or a timeout.