2
class Calc {
  constructor(num) {
    this.num = num;
  }

  add() {
    // code
  }

  subtract() {
    // code
  }

  multiply() {
    // code
  }

  divide() {
    // code
  }
}

const getRes = async () => {
  const res = await new Calc(10)
    .add(30)
    .subtract(5)
    .multiply(2);

    console.log(res) //prints the result
};

getRes();

How do i achieve this behaviour? I want to be able to chain all the methods (which in this example are add, subtract, multiply, divide) one after another and when i await them it should return the result same as when we await mongoose queries.

I know ordinary calculation isn't asynchronous, but imagine that the methods were asynchronous - what would the proper code to achieve the desired effect look like?

2
  • 1
    why do you need to await. are those function asynchronous? Commented Mar 3, 2020 at 4:27
  • @hussain.codes Yes, actually i'm trying to figure out how does mongoose chain its query functions (like sort, limit, select etc...). So let's assume that all of these functions are asynchronous and now how do i chain them? Commented Mar 3, 2020 at 4:48

1 Answer 1

4

You can return an object which has the add, subtract, etc methods on it. When those methods are invoked, reassign an internal property of the instance, which holds the Promise. At the end of the chain, access that Promise property on the instance:

class Calc {
  constructor(num) {
    this.prom = Promise.resolve(num);
  }

  add(arg) {
    this.prom = this.prom.then(res => res + arg);
    return this;
  }

  subtract(arg) {
    this.prom = this.prom.then(res => res - arg);
    return this;
  }

  multiply(arg) {
    this.prom = this.prom.then(res => res * arg);
    return this;
  }
}

const getRes = async () => {
  const res = await new Calc(10)
    .add(30)
    .subtract(5)
    .multiply(2)
    .prom;

    console.log(res) //prints the result
};

getRes();

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.