Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for browser environments #134

Merged
merged 1 commit into from
Jan 30, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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;
Copy link

@shivijais shivijais Feb 19, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@leebyron This will throw error in browsers which do not support setImmediate. SetImmediate polyfill is mandatory for this code to work. Something like this would be better
(typeof setImmediate !== 'undefined' ? setImmediate : setTimeout)

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just got bitten by this. @leebyron

Copy link

@xealot xealot Nov 5, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aye, same. Care here and saw this. Is this still not addressed?

To anyone using CoreJS, a workaround:

import 'core-js/web/immediate';


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