summaryrefslogtreecommitdiff
path: root/test/parallel/test-async-hooks-execution-async-resource-await.js
blob: 8dc04c83d731034437ff9a483a901293b27f37c4 (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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
'use strict';

const common = require('../common');
const sleep = require('util').promisify(setTimeout);
const assert = require('assert');
const { executionAsyncResource, createHook } = require('async_hooks');
const { createServer, get } = require('http');
const sym = Symbol('cls');

// Tests continuation local storage with the currentResource API
// through an async function

assert.ok(executionAsyncResource());

createHook({
  init(asyncId, type, triggerAsyncId, resource) {
    const cr = executionAsyncResource();
    resource[sym] = cr[sym];
  }
}).enable();

async function handler(req, res) {
  executionAsyncResource()[sym] = { state: req.url };
  await sleep(10);
  const { state } = executionAsyncResource()[sym];
  res.setHeader('content-type', 'application/json');
  res.end(JSON.stringify({ state }));
}

const server = createServer(function(req, res) {
  handler(req, res);
});

function test(n) {
  get(`http://localhost:${server.address().port}/${n}`, common.mustCall(function(res) {
    res.setEncoding('utf8');

    let body = '';
    res.on('data', function(chunk) {
      body += chunk;
    });

    res.on('end', common.mustCall(function() {
      assert.deepStrictEqual(JSON.parse(body), { state: `/${n}` });
    }));
  }));
}

server.listen(0, common.mustCall(function() {
  server.unref();
  for (let i = 0; i < 10; i++) {
    test(i);
  }
}));