如何链接异步方法

时间:2018-04-11 03:46:44

标签: javascript asynchronous method-chaining

我编写的API有几个不返回值的异步方法,但仍应按它们被调用的顺序执行。我想从最终用户那里抽象出等待的解决方案,以便他们可以链接方法调用,并期望在解决上一个问题之后执行每个promise:

api = new Api();
api.doAsync().doAnotherAsync().doAThirdAsync();

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

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

doAsync方法都会按照_chain这样推迟

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

我知道我可以像这样写

async doAsync() {
    // do async thing
    return this;
}

并像这样使用

doAsync.then(api => api).then(...)

但是,如果可以的话,明确地从每个this调用返回then对象是我想要避免的,它只是看起来像{{1}的同步方式一样干净}

2 个答案:

答案 0 :(得分:1)

您不需要某种API对象来链接async函数。如果他们不接受您的示例代码所指示的输入值,那么纯粹的promise链式方法几乎完全相同,没有任何样板:

async function delay (ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms)
  })
}

async function log (message) {
  console.log(message)
}

async function delay1s () {
  return delay(1000)
}

async function logNow () {
  const seconds = Math.round(performance.now() / 1000)

  return log(`${seconds}s`)
}

log('start')
  .then(delay1s)
  .then(logNow)
  .then(delay1s)
  .then(logNow)
  .then(delay1s)
  .then(() => log('stop'))

正如你所看到的,即使是接受输入的函数也只需要包含在一个匿名的箭头函数中,这个函数非常简单,而且远非难以理解。

答案 1 :(得分:1)

你可以从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

我们可以添加其他更有用的功能。注意,因为我们正在使用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

添加您现在想要的任何功能。此示例显示了实际执行更真实的功能

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