为什么不。然后在异步函数前面。那么之后执行?
多重调用有时_dispatch
导致传递给_dispatch
同时要执行的承诺。不应该。那么以前的。然后后执行?
// Failing code
async _dispatch (promise) {
// this._mutex is a Promise
this._mutex = this._mutex.then(() => promise)
return Promise.resolve(this._mutex)
}
// Possibly working code
async _dispatch (promise) {
console.log('START_CS', promise)
while (Atomics.load(this.done, 0) === 0) {
await this.sleep(50)
}
Atomics.store(this.done, 0, 0)
console.log('IN_CS', promise)
const ret = await promise
Atomics.store(this.done, 0, 1)
console.log('END_CS', promise)
return ret
}
_dispatch
以下列方式使用:
async getStatus (ports) {
const request = // ...
return this._dispatch(someAsyncFunctionReturningArray(request, ports))
}
const polling = () => {
const sleep = new Promise(resolve => setTimeout(resolve, 500))
const status = this.getStatus().then(() => {}).catch(() => {})
return Promise.all([sleep, status])
.then(polling)
}
polling()
轮询()和另一个代码相似的块在同一时间运行。我注意到,someAsyncFunctionReturningArray
被同时调用。
承诺履行有关任务的状态信息,并允许你采取行动的那种状态。他们不这样做,一般情况下,代表任务本身。下面是你在做什么等价的:
async function foo() {
console.log('foo() task ran');
}
function delay() {
return new Promise(resolve => {
setTimeout(resolve, 1000);
});
}
const promise = foo();
delay().then(() => promise)
这不会是由第二延迟promise
,因为promise
仅仅是可以说“解决了与值X”,“错误Ÿ拒绝”或“待定”的对象。有没有拖延承诺概念 - 你拖延的任务。这项工作是由foo
和启动时调用foo()
完成。
这不是很清楚正确的替换将是你的问题是什么。我想,这是你所追求的:
_dispatch (action) {
this._mutex = this._mutex.then(() => action())
return this._mutex
}
async getStatus (ports) {
const request = // ...
return this._dispatch(() => someAsyncFunctionReturningArray(request, ports))
}
但它可能有这效果更好完全不同的方法,而我们需要对你想用此队列来完成推荐一个什么样的更多细节。