dataloader icon indicating copy to clipboard operation
dataloader copied to clipboard

Ever considered the use of `queueMicrotask`?

Open andreyvital opened this issue 2 years ago • 1 comments

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

https://github.com/graphql/dataloader/blob/d336bd15282664e0be4b4a657cb796f09bafbc6b/src/index.js#L239-L255

Just a question...

Thanks, A.

andreyvital avatar Aug 17 '23 15:08 andreyvital

@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.

victorandree avatar Dec 18 '23 10:12 victorandree