Skip to content

Commit

Permalink
Merge bbaa9a1 into 6454b14
Browse files Browse the repository at this point in the history
  • Loading branch information
xaviergonz committed Apr 4, 2020
2 parents 6454b14 + bbaa9a1 commit 4ec73e5
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
@@ -1,3 +1,5 @@
* Another fix for invalid `actionAsync` context when promises resolve at the same time in different actionAsync calls, by [xaviergonz](https://github.com/xaviergonz) through [#244](https://github.com/mobxjs/mobx-utils/pull/244)

# 5.5.5

* Fixed tree-shaking mobx-utils, see [#238](https://github.com/mobxjs/mobx-utils/pull/238) by [IgorBabkin](https://github.com/IgorBabkin)
Expand Down
29 changes: 24 additions & 5 deletions src/action-async.ts
Expand Up @@ -16,8 +16,29 @@ interface IActionAsyncContext {
args: IArguments
}

let taskOrderPromise = Promise.resolve()
const emptyFunction = () => Promise.resolve()
let taskOrderPromise: Promise<any> = Promise.resolve()

let queueMicrotaskPolyfill: typeof queueMicrotask

if (typeof queueMicrotask !== "undefined") {
// use real implementation if possible
queueMicrotaskPolyfill = queueMicrotask
} else if (typeof process !== "undefined" && process.nextTick) {
// fallback to node's process.nextTick in node <= 10
queueMicrotaskPolyfill = (cb: any) => {
process.nextTick(cb)
}
} else {
// use setTimeout for old browsers
queueMicrotaskPolyfill = (cb: any) => {
setTimeout(cb, 0)
}
}

const idle = () =>
new Promise(r => {
queueMicrotaskPolyfill(r)
})

const actionAsyncContextStack: IActionAsyncContext[] = []

Expand All @@ -41,9 +62,7 @@ export async function task<R>(value: R | PromiseLike<R>): Promise<R> {

// we use this trick to force a proper order of execution
// even for immediately resolved promises
// we need to also use catch or else it won't work for older versions of node (< 10)
// since it would resolve them immediately
taskOrderPromise = taskOrderPromise.then(emptyFunction).catch(emptyFunction)
taskOrderPromise = taskOrderPromise.then(idle)
await taskOrderPromise

return ret
Expand Down

0 comments on commit 4ec73e5

Please sign in to comment.