如何链接异步方法

ric*_*i90 4 javascript asynchronous method-chaining

我编写的 API 有几个不返回值的异步方法,但仍应按调用顺序执行。我想从最终用户中抽象出正在等待的解决方案,以便他们可以链接方法调用,并期望每个承诺在前一个承诺解决后执行,如下所示:

api = new Api();
api.doAsync().doAnotherAsync().doAThirdAsync();
Run Code Online (Sandbox Code Playgroud)

我们从这些方法中获取值并不重要,重要的是它们按顺序执行。我尝试过使用链接结构,但它并不可靠。

class Api {
    resolvingMethodChain = false;
    constructor() {
        this._methodChain = {
            next: null,
            promise: Promise.resolve(),
        }
    }

    _chain(p) {
        this._methodChain.next = {
            promise: p,
            next: null,
        };

        // if we are not finished resolving the method chain, just append to the current chain
        if (!this.resolvingMethodChain) this._resolveMethodChain(this._methodChain);

        this._methodChain = this._methodChain.next;
        return this
    }

    async _resolveMethodChain(chain) {
        if (!this.resolvingPromiseChain) {
            this.resolvingPromiseChain = true;
        }

        // base case
        if (chain === null) {
            this.resolvingPromiseChain = false;
            return;
        }

        // resolve the promise in the current chain
        await chain.promise;

        // resolve the next promise in the chain
        this._resolvePromiseChain(c.next);   
    }
}
Run Code Online (Sandbox Code Playgroud)

这些doAsync方法都会_chain像这样

doAsync() {
    const p = new Promise(// do some async stuff);
    return _chain(p); // returns this and adds the promise to the methodChain
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样写

async doAsync() {
    // do async thing
    return this;
}
Run Code Online (Sandbox Code Playgroud)

像这样使用它

doAsync.then(api => api).then(...)
Run Code Online (Sandbox Code Playgroud)

但是,如果可以的话,我想避免this从每次调用中显式返回对象,它只是看起来不像同步方式那么干净thenapi.doAsync().doAnotherAsync()...

Tha*_*you 5

您可以从 Promise 的简单包装开始

const effect = f => x =>
  (f (x), x)
  
const Api = (p = Promise.resolve ()) =>
  ({ foo: () => 
       Api (p.then (effect (x => console.log ('foo', x))))
     
   , bar: (arg) =>
       Api (p.then (effect (x => console.log ('bar', arg))))
     
  })
  
Api().foo().foo().bar(5)
// foo undefined
// foo undefined
// bar 5
Run Code Online (Sandbox Code Playgroud)

我们可以添加其他函数来做更多有用的事情。请注意,因为我们使用 Promises,所以我们可以轻松对同步或异步函数进行排序

const effect = f => x =>
  (f (x), x)
  
const square = x =>
  x * x
  
const Api = (p = Promise.resolve ()) =>
  ({ log: () =>
       Api (p.then (effect (console.log)))
       
   , foo: () => 
       Api (p.then (effect (x => console.log ('foo', x))))
     
   , bar: (arg) =>
       Api (p.then (effect (x => console.log ('bar', arg))))
  
   , then: f =>
       Api (p.then (f))
  })

  
Api().log().then(() => 5).log().then(square).log()
// undefined
// 5
// 25
Run Code Online (Sandbox Code Playgroud)

现在添加您想要的任何功能。这个例子展示了实际上做一些更现实的事情的函数

const effect = f => x =>
  (f (x), x)
  
const DB =
  { 10: { id: 10, name: 'Alice' }
  , 20: { id: 20, name: 'Bob' }
  }
  
const Database =
  { getUser: id =>
      new Promise (r =>
        setTimeout (r, 250, DB[id]))
  }
  
const Api = (p = Promise.resolve ()) =>
  ({ log: () =>
       Api (p.then (effect (console.log)))
       
   , getUser: (id) =>
       Api (p.then (() => Database.getUser (id)))
       
   , displayName: () =>
       Api (p.then (effect (user => console.log (user.name))))
  
  })

  
Api().getUser(10).log().displayName().log()
// { id: 10, name: 'Alice' }
// Alice
// { id: 10, name: 'Alice' }

Api().getUser(10).log().getUser(20).log().displayName()
// { id: 10, name: 'Alice' }
// { id: 20, name: 'Bob' }
// Bob
Run Code Online (Sandbox Code Playgroud)