-1

Hey, i am trying to return this console after 1000 milli sec using this promise, but for some reason it consoles before ending the setTime out. Any idea how I can get the console.log to happen after the timeOutPromise is finished?

const timeOutPromise = () => new Promise(resolve => { setTimeout(() => { resolve(); }, 1000); });

const thisPromise = (num1, num2) => new Promise((resolve, reject) => {
  timeOutPromise()
    .then(resolve(console.log(num1 + num2)))
    .catch(reject(Error));
});

thisPromise(1, 2);
  • [`then`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) and [`catch`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) expect a function to be passed. Neither `resolve(console.log(num1 + num2))` nor `reject(Error)` is a function. Also, `reject` should be passed an Error instance, not the `Error` constructor. – Sebastian Simon Feb 07 '22 at 00:15

1 Answers1

2

Your code is calling console.log synchronously when the promise is set up. You need to pass a callback to then, not the result of console.log(). Further, if you already have a promise, no need to wrap it in a promise constructor, just use chaining.

const timeOutPromise = () => new Promise(resolve => { setTimeout(() => { resolve(); }, 1000); });

const thisPromise = (num1, num2) => timeOutPromise()
    .then(() => console.log(num1 + num2))

thisPromise(1, 2);
CollinD
  • 7,304
  • 2
  • 22
  • 45