Search code examples
javascriptecmascript-6es6-promise

Promise method of then running before Promise is completed


In the following example, After the Promise is completed and aaa is printed, then only hello should be printed. But, it is not happening. Why, as .then method runs only after Promise is completed.

function printF(item){
  return new Promise((resolve, reject) => resolve(setTimeout(function(){console.log('aaa')}, 1000)));
}

printF(10).then(res => console.log('hello'));


Solution

  • If because you are resolving your promise immediately i.e. setTimeout is called inside of promise, so promise will be resolve immediately triggering .then part and then after 1 sec the setTimeout code will be executed.

    Instead, resolve promise after 1 second by taking wrapping the resolve inside setTimeout as -

    function printF(item) {
      return new Promise((resolve, reject) =>
        setTimeout(() => resolve(console.log('aaa')), 1000)
      );
    }
    
    printF(10).then(res => console.log('hello'));