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

Ever considered the use of queueMicrotask? #348

Open
andreyvital opened this issue Aug 17, 2023 · 1 comment
Open

Ever considered the use of queueMicrotask? #348

andreyvital opened this issue Aug 17, 2023 · 1 comment

Comments

@andreyvital
Copy link

andreyvital commented Aug 17, 2023

It's available as of v11—isn't it better than process.nextTick? https://nodejs.org/api/globals.html#queuemicrotaskcallback

dataloader/src/index.js

Lines 239 to 255 in d336bd1

const enqueuePostPromiseJob =
typeof process === 'object' && typeof process.nextTick === 'function'
? function (fn) {
if (!resolvedPromise) {
resolvedPromise = Promise.resolve();
}
resolvedPromise.then(() => {
process.nextTick(fn);
});
}
: typeof setImmediate === 'function'
? function (fn) {
setImmediate(fn);
}
: function (fn) {
setTimeout(fn);
};

Just a question...

Thanks,
A.

@victorandree
Copy link

@andreyvital I had the same thought when considering this library on something like Cloudflare Workers or Vercel (see #341).

I decided to investigate and TL;DR is that I don't think queueMicrotask can quite replicate the behavior of process.nextTick(fn) because of subtle differences in scheduling. This behavior is covered by this test: https://github.com/graphql/dataloader/blob/55c33d480cdf429a0b24cf607ddd0e892521a35b/src/__tests__/dataloader.test.js#L1004C5-L1025C5.

My understanding is this: The batch is constructed, and schedules its post-promise job, before the promises to return values are constructed. This means that the associated microtask would always be queued before those promises start resolving. I don't see a way to use the queueMicrotask to schedule its job "after" Promises. setTimeout (and setImmediate, though that's deprecated) will execute after, which is why they're the backup for process.nextTick.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants