Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chainable promise method

Tags:

javascript

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;
};
like image 801
Solo Avatar asked May 23 '26 20:05

Solo


1 Answers

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;
};
like image 190
Bergi Avatar answered May 26 '26 10:05

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!