javascript function chaining code example

Example 1: javascript promise chain

// base case 
promise
  .then(...)
  .then(...)
  .then(...)
  .catch(...)

//real world
coinflip(10)
  .then(betAgain)
  .then(betAgain)
  .then(betAgain)
  .then(result => {
    console.log(`OMG, WE DID THIS! TIME TO TAKE ${result} HOME!`);
  })
  .catch(handleRejection);

Example 2: method chaining in javascript

class Arithmetic {
  constructor() {
    this.value = 0;
  }
  sum(...args) {
    this.value = args.reduce((sum, current) => sum + current, 0);
    return this;
  }
  add(value) {
    this.value = this.value + value;
    return this;
  }
  subtract(value) {
    this.value = this.value - value;
    return this;
  }
  average(...args) {
    this.value = args.length
      ? (this.sum(...args).value) / args.length
      : undefined;
    return this;
  }
}

a = new Arithmetic()
a.sum(1, 3, 6)   // => { value: 10 } 
  .subtract(3)   // => { value: 7 }
  .add(4)        // => { value: 11 }
  .value         // => 11 

// Console Output
// 11

Example 3: method chaining

given() ....   --> RequestSpecification 
     .header  accept() contentType()
     .queryParam
     .pathParam
     .body
     .log
     .auth..
when()       --->> RequestSender
   .get() ------>> Response Object 
   .post()
   .put()
   .delete()
then()      -----> ValidatableResponse  
        This is where assertion happen 
    .statusCode
    .header   accept() contentType()
    .body( matchers goes here)
    .log