summaryrefslogtreecommitdiff
path: root/lib/internal/queue_microtask.js
blob: 6ca0c1e144a92b9a78922ece1e20d58fafe64dc2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
'use strict';

const { ERR_INVALID_ARG_TYPE } = require('internal/errors').codes;
const { AsyncResource } = require('async_hooks');
const { getDefaultTriggerAsyncId } = require('internal/async_hooks');
const {
  enqueueMicrotask,
  triggerFatalException
} = internalBinding('util');

function queueMicrotask(callback) {
  if (typeof callback !== 'function') {
    throw new ERR_INVALID_ARG_TYPE('callback', 'function', callback);
  }

  const asyncResource = new AsyncResource('Microtask', {
    triggerAsyncId: getDefaultTriggerAsyncId(),
    requireManualDestroy: true,
  });

  enqueueMicrotask(() => {
    asyncResource.runInAsyncScope(() => {
      try {
        callback();
      } catch (error) {
        // TODO(devsnek) remove this if
        // https://bugs.chromium.org/p/v8/issues/detail?id=8326
        // is resolved such that V8 triggers the fatal exception
        // handler for microtasks
        triggerFatalException(error);
      } finally {
        asyncResource.emitDestroy();
      }
    });
  });
}

module.exports = { queueMicrotask };