Skip to content

Commit 49e2659

Browse files
authored
Add support for browser environments (#134)
The secret sauce of this library is `enqueuePostPromiseJob`, which relies on node.js behavior of process.nextTick to behave correctly. Browsers must use a macro-task to achieve similarly correct behavior, though it may have performance implications.
1 parent 7404ab2 commit 49e2659

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

src/index.js

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -205,12 +205,20 @@ export default class DataLoader<K, V> {
205205
// In order to avoid the DataLoader dispatch Job occuring before "PromiseJobs",
206206
// A Promise Job is created with the sole purpose of enqueuing a global Job,
207207
// ensuring that it always occurs after "PromiseJobs" ends.
208-
function enqueuePostPromiseJob(fn) {
209-
if (!resolvedPromise) {
210-
resolvedPromise = Promise.resolve();
211-
}
212-
resolvedPromise.then(() => process.nextTick(fn));
213-
}
208+
//
209+
// Node.js's job queue is unique. Browsers do not have an equivalent mechanism
210+
// for enqueuing a job to be performed after promise microtasks and before the
211+
// next macrotask. For browser environments, a macrotask is used (via
212+
// setImmediate or setTimeout) at a potential performance penalty.
213+
var enqueuePostPromiseJob =
214+
typeof process === 'object' && typeof process.nextTick === 'function' ?
215+
function (fn) {
216+
if (!resolvedPromise) {
217+
resolvedPromise = Promise.resolve();
218+
}
219+
resolvedPromise.then(() => process.nextTick(fn));
220+
} :
221+
setImmediate || setTimeout;
214222

215223
// Private: cached resolved Promise instance
216224
var resolvedPromise;

0 commit comments

Comments
 (0)