Linked Questions

Popular Questions

Multiple calls to _dispatch sometimes causes the promises passed to _dispatch to be executed at the same time. Isn't .then supposed to execute after previous .then?

// 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 is used in the following manner:

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()

polling() and another similar block of code is running at the same time. I noticed that someAsyncFunctionReturningArray is called concurrently.

Related Questions