0

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'));
Ahmad MOUSSA
  • 2,729
  • 19
  • 31
Deadpool
  • 7,811
  • 9
  • 44
  • 88
  • in the current form of the question the code shown resolves then calls the then method given, I don't think the question asked is possible with any current implementation... perhaps consult the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – jimmont Dec 18 '20 at 09:14

1 Answers1

2

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'));
Nikhil Patil
  • 2,480
  • 1
  • 7
  • 20