-6

The below script works, but I don't understand why one doesn't have to

const a = promisify(opA());

instead of the (correct)

const a = promisify(opA);

I mean opA is a function, so why not opA()?

'use strict'
const { promisify } = require('util')

const opA = (cb) => {
  setTimeout(() => {
    cb(null, 'A')
  }, 500)
}

const opB = (cb) => {
  setTimeout(() => {
    cb(null, 'B')
  }, 250)
}

const opC = (cb) => {
  setTimeout(() => {
    cb(null, 'C')
  }, 125)
}

const a = promisify(opA);
const b = promisify(opB);
const c = promisify(opC);

(async function() {
  try {
    console.log(await a());
    console.log(await b());
    console.log(await c());
  } catch(err) {
    print(err);
  };
})();
Sandra Schlichting
  • 25,050
  • 33
  • 110
  • 162
  • Because `promisify` is a higher-order function. Notice that `a` also is a function. What could calling `a()` do if you had passed `opA()` to `promisify`? Did you check what the return value of `opA()` is? – Bergi Sep 09 '21 at 23:03
  • 2
    Does this answer your question? [In JavaScript, does it make a difference if I call a function with parentheses?](https://stackoverflow.com/questions/3246928/in-javascript-does-it-make-a-difference-if-i-call-a-function-with-parentheses) – Sebastian Simon Sep 09 '21 at 23:07

1 Answers1

3

I mean opA is a function, so why not opA()?

Because opA is a reference to the function itself. The promise will use that reference to execute that function at a later time.

Alternatively, opA() executes the function (without any arguments) now and passes the result of that function call to the promise. Since your opA function doesn't return anything, it would pass undefined to the promise. The promise would then have nothing to execute later after it completes its operation(s). The setTimeout would then also fail because cb is also undefined, because no arguments were passed to opA().

Any time you do see a structure like that, either (1) it's a bug or (2) the function intentionally builds and returns a callback function intended for the promise. For example, if you write a function which returns opA then you can invoke that function and pass its result to promisify.


An important clue to this behavior is here:

const opA = ...

opA is a variable, not unlike any other variable. It contains a value or a reference to something. In this case it's a reference to a function. You could re-assign that variable, pass it as a function argument, set it as a property on an object, etc. just like any other.

David
  • 208,112
  • 36
  • 198
  • 279