0

Can someone explain why in this scenario the results are different? I mean, in the last block the second call does wait for the 'setTimeOut'. Can't I pass the parameter as I did?

function awaitFor(seconds = 2000) {
    return new Promise(function (resolve) {
        setTimeout(() => resolve(), seconds)
    })
}

/** Why this */
awaitFor(2000)
    .then(() => console.log('Executing promise 1'))
    .then(() => awaitFor(2000))
    .then(() => console.log('Executing promise 2'))

awaitFor(2000)
    .then(() => console.log('Executing promise 1'))
    .then(awaitFor)
    .then(() => console.log('Executing promise 2'))

/** Is different than this? */
awaitFor(2000)
    .then(() => console.log('Executing promise 1'))
    .then(awaitFor(2000))
    .then(() => console.log('Executing promise 2'))
  • 1
    Consider the **types** of the things you are passing to `.then()`. A Promise is an `Object` that has a `.then()` method/function. Both `awaitFor` and `() => {}` are `Function`s. So in the first one you are passing `.then(Function)`. In the second one you are passing `.then(Function)`. In the third one you are passing `.then(Object)`. The `.then()` method in the third attempt is trying to call that object as if it is a function - which of course does not work so it does nothing and pass on control to the next `.then()` – slebetman Jul 26 '22 at 02:42
  • In the first case, you passed `() => awaitFor(2000)` to `then`. This is considered a separate function, and therefore is not called immediately. When it's called, it will ignore the argument passed to it, and use awaitFor(2000) as the return value. In the second case, you passed `awaitFor`. But the return value of console.log is `undefined` so it will attempt to call `awaitFor(undefined)` which, due to `seconds=2000` in your function becomes `awaitFor(2000)`. Note that this 'seconds' is a misleading variable name, it'd be better called milliseconds. – qrsngky Jul 26 '22 at 02:54
  • In the third case, you passed `awaitFor(2000)` but this will be evaluated here and the return value will be passed to then. So it's like using `.then(promise_object)`, where `promise_object = awaitFor(2000)`. But this promise_object is not a function so it won't be called, it'll just pass the control to the next then-handler. – qrsngky Jul 26 '22 at 02:54
  • `The .then() method in the third attempt is trying to call that object as if it is a function` not quite ... `.then` simply ignores any argument that isn't a function as if it were not present and simply returns the incoming promise - the reason passing a non-function to the first argument of `.then` isn't considered an error is so that the `onRejected` second argument can be given without needing a valid onResolved first argument – Jaromanda X Jul 26 '22 at 03:14

0 Answers0