3

How to make the following chainable methods work?

I.e promise method should wrap the data returned from get into promise.

// I need to do both:

// return object directly
return client.get(args);

// return promise
return client.get(args).promise();

Why? There's a library that uses this signature and I need to mock it for testing.


Edit: answer applied

client.get = function(args) {
  let obj = {foo: 'bar'}; // get data from somewhere
  obj.promise = function() {
      return new Promise((resolve, reject) => {
        console.log(this); // {foo: 'bar'}
        resolve(this);
        // TODO: reject logic
      });
  };
  return obj;
};
Solo
  • 6,687
  • 7
  • 35
  • 67
  • No, you should absolutely not use `Object.setrototypeOf` here. – Bergi Feb 24 '19 at 13:34
  • @Bergi Yeah, you're right, did some research on that. – Solo Feb 24 '19 at 14:35
  • @Bergi I am interested in knowing why not to use `Object.setPrototypeOf` here? – Prakash Sharma Feb 28 '19 at 17:53
  • 1
    @PrakashSharma a) because it's the wrong tool, there is no use for inheritance here b) because it [generally should be avoided](https://stackoverflow.com/q/23807805/1048572) – Bergi Feb 28 '19 at 17:55
  • @Bergi Thanks. But I think your answer also has some problem. You are suggesting to add a new property to returned object itself. In that case operations like `Object.keys` might give different result then expected. – Prakash Sharma Feb 28 '19 at 18:13
  • As suggested in your linked answer, `Object.create` could be the right way. – Prakash Sharma Feb 28 '19 at 18:15
  • 1
    @PrakashSharma If that really is an issue, you could use `Object.defineProperty` to make it non-enumerable. But I'm not sure what the OP is really doing here so I can only speculate – Bergi Feb 28 '19 at 18:15
  • @Bergi Ok. Make sense. – Prakash Sharma Feb 28 '19 at 18:22

1 Answers1

2

You seem to be looking for

client.get = function(args) {
  let obj = {foo: 'bar'}; // get data from somewhere
  obj.promse = function() {
    return Promise.resolve(this);
  };
  return obj;
};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375