简体   繁体   中英

Using regenerator runtime with NodeJS

I'm trying to require the regeneratorRuntime object so that it's globally available, so my Node.js code will work with any async functions / generators babel transpiles for me anywhere in my application. regenerator was installed via npm npm install regenerator .

My question is, why does this code

require('regenerator/runtime');

console.log(typeof regenratorRuntime);
if (typeof regenratorRuntime === 'object'){
    console.log(typeof regenratorRuntime.wrap);
    console.log(typeof regenratorRuntime.awrap);
    console.log(typeof regenratorRuntime.async);
    console.log(typeof regenratorRuntime.mark);
}

not work as expected, leading to an undefined being logged, while replacing the first line with

global.regenratorRuntime = require('regenerator/runtime');

leads to expected results.

Looking in the runtime file I see this code

runtime = global.regeneratorRuntime = inModule ? module.exports : {};

in an IIFE with this expression passed in as global

(
  // Among the various tricks for obtaining a reference to the global
  // object, this seems to be the most reliable technique that does not
  // use indirect eval (which violates Content Security Policy).
  typeof global === "object" ? global :
  typeof window === "object" ? window :
  typeof self === "object" ? self : this
);

which I would expect to properly set up regenratorRuntime on the global object.

I don't mind manually setting global.regenratorRuntime , but I would like to understand why it's necessary. It seems as though code Node executes from a require statement may be acting differently than I assumed.

As an ancillary matter, can anyone point out what the self check is checking for?

It does set

global.regeneratorRuntime
//          ^

not

global.regenratorRuntime

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM