Skip to content Skip to sidebar Skip to footer

Why Can't Promise.resolve Be Called As A Function?

Something that is bugging me and my colleague. Consider the following... const {map, compose} = require('ramda'); compose( console.log, map(Math.tan) )([1,2,3]); compose( c

Solution 1:

Promise.resolve refers to the resolve function without context object.

You want to call it with the proper context object. This can be done

  • by calling it on that context object, as in v => Promise.resolve(v), or
  • by creating a bound version of it, as in Promise.resolve.bind(Promise)

So, this would work:

compose(
  console.log,
  map(Promise.resolve.bind(Promise))
)([7,8,9]);

Remember that Javascript does not have classes. Functions have no owner. Objects can store functions in their properties, but that does not mean the function is owned by that object.

Another way is setting the context object explicitly, with Function#call or Function#apply:

function (v) {
    var resolve = Promise.resolve;
    return resolve.call(Promise, v);
}

Maybe it's best illustrated by focusing on something other than a method:

functionFoo() {
    this.bar = {some: "value"};
    this.baz = function () { returnthis.bar; };
}

var f = newFoo();
var b = f.bar;
var z = f.baz;

here b refers to {some: "value"} without {some: "value"} magically "knowing" that f stores a reference to it. This should be obvious.

The same is true of z. It stores a function without that function "knowing" that f also references it. This should be just as obvious, in theory.

Calling z() will yield different results than calling f.baz(), even though the called function is the same one. Only the context is different.

Solution 2:

When a function is called its this variable is dynamically allocated a value.

The resolve function cares what that value is.

The third part of your code passes the resolve function and then calls it without the context of the Promise object.

This means that this does not get allocated the value of Promise which the function needs.

Solution 3:

Promise.resolve needs to be called with this being a Promise constructor (or subclass).

resolve = Promise.resolve;
resolve(null); // Error
resolve.call({}); // Error: Object is not a constructor

So change this line:

map(Promise.resolve)

to:

map(Promise.resolve.bind(Promise))

Post a Comment for "Why Can't Promise.resolve Be Called As A Function?"