关于链式调用其实我就一直没太弄明白, 之前有过一个blog, 现在发现, 值得再研究一下.

原来遗留了2个点.
  1. promise实现链式调用, 这个之前没弄.
  2. this尽量少用.
回顾了一下, 觉得比较好的写法.
//prototype+function写法
function test(){  //构造函数, 这种形式this是安全的.
  console.log('test called')   
}
test.prototype.someFunc=function() {
  console.log('someFunc')
  return this
}
test.prototype.someOtherFunc=function() {
  console.log('someOtherFunc')
  return this
}
var xxx = new test(); //因为是这么弄得.
xxx.someFunc().someOtherFunc();

但是, 这个写法并不好, 非常的死板, 调用时基于全局对象的, 也就是说全局都是唯一的一个单例对象才行. 至少是一个类, new了一个a对象, 然后再new一个b对象, 他们之间就无法链式调用了.

因此, 链式调用最好能基于返回值来做.

async/await语法糖是这样的:

async function foo() {
  try {
    let result = await doSomething();
    let newResult = await doSomethingElse(result);
    let finalResult = await doThirdThing(newResult);
    console.log(`Got the final result: ${finalResult}`);
  } catch(error) {
    failureCallback(error);
  }
}

因此, 目前js没有太好的链式调用方法.

promise是这样的:

doSomething()
.then(result => doSomethingElse(value))
.then(newResult => doThirdThing(newResult))
.then(finalResult => console.log(`Got the final result: ${finalResult}`))
.catch(failureCallback);
后记
  • 使用stampit, 链式调用很方便.