main
js 49 lines 1.83 KB
Raw
1 /**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @flow
8 */
9
10 let didWarnAboutMessageChannel = false;
11 let enqueueTaskImpl = null;
12
13 export default function enqueueTask(task: () => void): void {
14 if (enqueueTaskImpl === null) {
15 try {
16 // read require off the module object to get around the bundlers.
17 // we don't want them to detect a require and bundle a Node polyfill.
18 const requireString = ('require' + Math.random()).slice(0, 7);
19 // $FlowFixMe[invalid-computed-prop]
20 const nodeRequire = module && module[requireString];
21 // assuming we're in node, let's try to get node's
22 // version of setImmediate, bypassing fake timers if any.
23 enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate;
24 } catch (_err) {
25 // we're in a browser
26 // we can't use regular timers because they may still be faked
27 // so we try MessageChannel+postMessage instead
28 enqueueTaskImpl = function (callback: () => void) {
29 if (__DEV__) {
30 if (didWarnAboutMessageChannel === false) {
31 didWarnAboutMessageChannel = true;
32 if (typeof MessageChannel === 'undefined') {
33 console.error(
34 'This browser does not have a MessageChannel implementation, ' +
35 'so enqueuing tasks via await act(async () => ...) will fail. ' +
36 'Please file an issue at https://github.com/facebook/react/issues ' +
37 'if you encounter this warning.',
38 );
39 }
40 }
41 }
42 const channel = new MessageChannel();
43 channel.port1.onmessage = callback;
44 channel.port2.postMessage(undefined);
45 };
46 }
47 }
48 return enqueueTaskImpl(task);
49 }