-
-
Couldn't load subscription status.
- Fork 33.6k
Description
- Version:
12.0.0-pre(d6f6d7f8541327b72667d38777c47from master) and10.15.1 - Platform:
Linux myhostname 4.4.0-143-generic #169-Ubuntu SMP Thu Feb 7 07:56:38 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux - Subsystem: util
When calling util.callbackify on an async function. The returned function has a wrong length value. It also has the wrong prototype:
> asyncFn = async (a, b) => Promise.resolve(a+b)
[AsyncFunction: asyncFn]
> cbFunction = util.callbackify(asyncFn)
[AsyncFunction: asyncFn] // questionable, it's actually not an AsyncFunction anymore
> cbFunction.length
2 // plain wrong, should be three, since there's an parameter added
> Object.getPrototypeOf(cbFunction).constructor.name
'AsyncFunction' // it's not.length property:
Some libraries actually act differently based on the length of a function (express, for example: if a handler has a length of four, it's an error handler).
Since the returned function has one argument added, it should also add one to the length of the new function. I'm aware that there are several constructs
where the length parameter is wrong (functions that are accessing the arguments, functions defined with ... in the parameter list, etc), but this
breaks almost all cases and there seems to be no nice workaround to me.
The library I'm dealing with has hooks and it gets determined if they are asyncronous or syncronous based on their length (like legacy mocha used to do).
prototype:
I understand where this is coming from. There are libraries (like knex) that use the builder pattern and have a then
method in their protoype chain for convenience.
(please ignore that knex also provides a callback interface, as this is to make an argument for the current behaviour):
const query = knex('table').select('*')
.where({column: 4}) // has a then method
const execute = callbackify(query).bind(query); // this works because the query's prototype is set.
execute(cb);In this case, it might be fine as long as the query's prototype has Function in his prototype chain. If not, it is highly confusing to have a function that does not have a normal function's methods.
I've looked at the original PR that brought and found a comment that stated it would make not that much difference (note that this is the promisify introducing PR, but the callbackify one states that it is based upon it).
A definitley not async Function gets the AsyncFunction.prototype.
Afaik this is just confusing when debugging for now. It does not seem to have any methods on it (until someone sets a map method on it).