简体   繁体   中英

Chaining multiple asynchronous functions in javascript

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM