【发布时间】:2018-04-11 03:46:44
【问题描述】:
我编写的 API 有几个不返回值的异步方法,但仍应按调用顺序执行。我想从最终用户那里抽象出等待的解决方案,以便他们可以链接方法调用并期望每个承诺在前一个被解决后执行,如下所示:
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(...)
但是如果可以的话,我想避免从每个then 调用中显式返回this 对象,它看起来不像api.doAsync().doAnotherAsync()... 的同步方式那么干净
【问题讨论】:
-
如何正常使用promise do_Something().then(...).then(...) 等是一个简单的promise链,每个在前一个解决时执行,当其中的操作(本质上是异步)以一种或另一种方式完成时,每个承诺都会得到解决。
-
这最终会看起来像这样
doSomething().then(api => api).then(...)我只是想避免每次都显式返回 promise 在回调中返回的内容。
标签: javascript asynchronous method-chaining