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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Node js. How to share an array between two functions? Is there any less complicated way without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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… ☺️

Answer

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.

We are here to answer your question about Node js. How to share an array between two functions? Is there any less complicated way - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji