zoukankan      html  css  js  c++  java
  • Node 模块循环引用问题

    写作背景

    循环引用是模块系统里一个避免不了的话题,可以加以讨论

    Cycles

    When there are circular require() calls, a module might not have finished executing when it is returned.

    当在代码中出现循环 require 引用时,模块可能不会在返回结果前结束执行

    Consider this situation:

    考虑这个情景:

    a.js

    console.log('a starting');
    exports.done = false;
    const b = require('./b.js');
    console.log('in a, b.done = %j', b.done);
    exports.done = true;
    console.log('a done');
    

    b.js

    console.log('b starting');
    exports.done = false;
    const a = require('./a.js');
    console.log('in b, a.done = %j', a.done);
    exports.done = true;
    console.log('b done');
    

    main.js

    console.log('main starting');
    const a = require('./a.js');
    const b = require('./b.js');
    console.log('in main, a.done=%j, b.done=%j', a.done, b.done);
    

    When main.js loads a.js, then a.js in turn loads b.js. At that point, b.js tries to load a.js. In order to prevent an infinite loop, an unfinished copy of the a.js exports object is returned to the b.js module. b.js then finishes loading, and its exports object is provided to the a.js module.

    当 main.js 加载 a.js 时,a.js 依次加载 b.js。这时,b.js 试图加载 a.js。为了防止无限循环,将 a.js exports 对象的未完成副本返回给 b.js 模块(就是 const b = require('./b.js'); 的上面那行 exports.down = false;)。 然后 b.js 完成加载,并将其导出对象提供给 a.js 模块。

    By the time main.js has loaded both modules, they're both finished. The output of this program would thus be:

    此时 main.js 完成对这两个模块的加载,最后程序的输出如下:

    $ node main.js
    main starting
    a starting
    b starting
    in b, a.done = false
    b done
    in a, b.done = true
    a done
    in main, a.done=true, b.done=true
    

    Careful planning is required to allow cyclic module dependencies to work correctly within an application.

    要小心设计模块,来使得循环模块依赖项能在程序里正常工作。

    通常循环引用后最后碰上 undefined,因为它并不会在代码中段 exports 值,import 的时候就只会是 undefined。

    总结

    总的来说,循环依赖的陷阱并不大容易出现,但一旦出现了,对于新手来说还真不好定位。它的存在给我们提了个醒,要时刻注意你项目的依赖关系不要过于复杂,哪天你发现一个你明明已经 exports 了的方法报 undefined is not a function,那就该警醒。

    写到这里才发现原来 Node 官网早已经有了中英文对照版本,不过我还是为文一记吧。

  • 相关阅读:
    leetcode--Search for a Range
    leetcode--Valid Palindrome
    leetcode--Validate Binary Search Tree
    leetcode--Count and Say
    leetcode--Partition List
    C语言atof()函数:将字符串转换为double(双精度浮点数)
    程序员与科学家的区别
    mingw编译rtmp库
    使用printf输出各种格式的字符串( 转载)
    c++使用stdint.h和inttypes.h
  • 原文地址:https://www.cnblogs.com/everlose/p/12840186.html
Copyright © 2011-2022 走看看