wrap-async-context

    1.0.4 • Public • Published

    wrap-async-context

    Uses node's experimental AsyncWrap to share 'global' data across related async operations.

    Usage:

    import context, { createContext } from 'wrap-async-context';
     
    function doABunchOfAsyncThings() {
      createContext(getId(), { data: 'yay' });
      setTimeout(function() {
        doSomeOtherAsyncThing();
      }, 100);
    }
     
    // elsewhere:
    function doSomeOtherAsyncThing() {
      console.log(context().data);
      // prints 'yay'
    }

    contrived express example:

    Passing a request ID to other services for logging/monitoring.

    import uuid from 'node-uuid';
    import { createContext } from 'wrap-async-context';
     
    app.use((req, res, next) => {
      createContext(req.headers['x-request-id'] || uuid.v4(), { req });
      next();
    });
     
    app.get('/something', (req, res) => {
      otherService.loadUser();
    });
     
    // In otherService.js:
    function loadUser() {
      return fetch('http://example.com/load-user', {
        headers: { 'x-request-id': context().id },
      });
    }

    Install

    npm i wrap-async-context

    DownloadsWeekly Downloads

    6

    Version

    1.0.4

    License

    MIT

    Last publish

    Collaborators

    • somehats