Search code examples
node.jssynchronizationatomic

Node js. How to share an array between two functions? Is there any less complicated way


I am very new to nodejs and stuck at a place where one function populates an array and the other reads from it.

Is there any simple construct to synchronize this.

Code looks something like Below

let arr = [];
let prod = function() {
    arr.push('test');
};

let consume = function() {
    process(arr.pop());
};

I did find some complicated ways to do it :(

Thanks alot for any help... ☺️


Solution

  • By synchronizing you probably mean that push on one side of your application should trigger pop on the other. That can be achieved with not-so-trivial event-driven approach, using the NodeJS Events module.

    However, in simple case you could try another approach with intermediary object that does the encapsulation of array operations and utilizes the provided callbacks to achieve observable behavior.

    // Using the Modular pattern to make some processor
    // which has 2 public methods and private array storage
    const processor = () => {
      const storage = [];
    
      // Consume takes value and another function
      // that is the passed to the produce method
      const consume = (value, cb) => {
        if (value) {
          storage.push(value);
          produce(cb);
        }
      };
    
      // Pops the value from storage and
      // passes it to a callback function
      const produce = (cb) => {
        cb(storage.pop());
      };
    
      return { consume, produce };
    };
    
    // Usage
    processor().consume(13, (value) => {
      console.log(value);
    });
    

    This is really a noop example, but I think that this should create a basic understanding how to build "synchronization" mechanism you've mentioned, using observer behavior and essential JavaScript callbacks.