Promise resolves to null when resolving this

Viewed 5461

I have a function that connects to a API. That function returns a Promise. I can't figure out why Promise.resolve returns null when I'm resolving with a constant containing the this context.

const connect = () => {
  return new Promise((resolve, reject) => {
    Gitana.connect(config, function(err) {
      const platform = this;
      if (err) {
        return reject(err);
      }
      console.log(platform) // Object that I want
      resolve(platform)
    });
  });
}

connect()
  .then(platform => {
    console.log(platform) // null
  })

I don't know if it is any help but I know there is a method on the resolve object (platform) called datastore. If I resolve that method, ie resolve(platform.datastore) I get the method, instead of null

I have tried to resolve static values, resolve(25) or resolve('hello') and that works fine.

How do I return/resolve the object?

2 Answers

As you've noted, it looks like this is happening because the value you're trying to pass actually has a .then method, so it is being subsumed in the promise resolution procedure.

One way to pass it without deleting methods would be to wrap it in a container to transport it along:

const connect = () => {
  return new Promise((resolve, reject) => {
    Gitana.connect(config, function(err) {
      const platform = this;
      if (err) {
        return reject(err);
      }
      resolve({ platform });
    });
  });
}

connect()
  .then(({ platform }) => {
    console.log(platform)
  })

Turns out that platform, the object to resolve, also has a then method. If you resolve the original promise with a new promise then it will try to resolve the new one as well. In this case the new promise resolves to null.

const connect = () => {
  return new Promise((resolve, reject) => {
    Gitana.connect(config, function(err) {
      const platform = this;
      if (err) {
        return reject(err);
      }
      delete platform.this;
      resolve(platform);
    });
  });
}

The next question is how to do this in a better way than deleting every obsolete then method.

Related