2

The way I see it, there are three ways to promisify and call a method function in one shot:

const { promisify } = require('util');

const obj = {
    method: function (param, callback) {
        // Do something async with `this`
        callback(err, result);
    }
};

promisify(obj.method.bind(obj))(arg).then(doSomething); // {1}
promisify(obj.method).bind(obj)(arg).then(doSomething); // {2}
promisify(obj.method).call(obj, arg).then(doSomething); // {3}

Are any of these methods preferred over the others, or are they all equally valid? What are the advantages and disadvantages of each?

Josh Klodnicki
  • 585
  • 6
  • 18
  • I'd say it depends on whether the method is a prototype method or an instance method, if you are calling the promisified version only once or multiple times, and (in the latter case) whether you are going to call it on the same instance every time or different ones. – Bergi Apr 27 '20 at 13:56
  • Some discussion in [How to use util.promisify and .bind functions in NodeJs?](https://stackoverflow.com/q/56143158/1048572) – Bergi Oct 01 '22 at 18:07
  • @Bergi I appreciate the follow-up. Your link doesn't quite answer my question, but a few clicks further, [this comment](https://github.com/nodejs/node/pull/13440#issuecomment-306002570) raises an interesting concern. Might #1 be problematic in the case where `[kCustomPromisifiedSymbol]` is set...? – Josh Klodnicki Oct 05 '22 at 13:52
  • Yes indeed, that's a good reason to prefer #2 over #1 if the method has custom promisification. – Bergi Oct 05 '22 at 19:46
  • If you really want to "*promisify and call a method function in one shot*", I'd definitely recommend `.call()` (#3). That's what it was made for. – Bergi Oct 05 '22 at 19:47

0 Answers0