Skip to content

Commit

Permalink
Add support for browser environments (#134)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
leebyron authored Jan 30, 2018
1 parent 7404ab2 commit 49e2659
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -205,12 +205,20 @@ export default class DataLoader<K, V> {
// In order to avoid the DataLoader dispatch Job occuring before "PromiseJobs",
// A Promise Job is created with the sole purpose of enqueuing a global Job,
// ensuring that it always occurs after "PromiseJobs" ends.
function enqueuePostPromiseJob(fn) {
if (!resolvedPromise) {
resolvedPromise = Promise.resolve();
}
resolvedPromise.then(() => process.nextTick(fn));
}
//
// Node.js's job queue is unique. Browsers do not have an equivalent mechanism
// for enqueuing a job to be performed after promise microtasks and before the
// next macrotask. For browser environments, a macrotask is used (via
// setImmediate or setTimeout) at a potential performance penalty.
var enqueuePostPromiseJob =
typeof process === 'object' && typeof process.nextTick === 'function' ?
function (fn) {
if (!resolvedPromise) {
resolvedPromise = Promise.resolve();
}
resolvedPromise.then(() => process.nextTick(fn));
} :
setImmediate || setTimeout;

// Private: cached resolved Promise instance
var resolvedPromise;
Expand Down

0 comments on commit 49e2659

Please sign in to comment.