Javascript Guarantee that function will not run in parallel

Spread the love

Sometimes we need to ensure that a function is called only once at a time, and other calls to the function should be awaited in queue till the earlier calls are completed. We can achieve this with Javascript using the promises. Let’s see the code below:

_callQueue: {
    arg1: string,
    arg2: string,
    res: (value: any) => void;
  }[] = [];
  _cruncherRunning = false;

 // add call to queue 
 heavyCalculationFunction = async (
    arg1: string,
    arg2: string,
  ) => {
    const promise = new Promise<any>(res =>
      _callQueue.push({ar1, arg2, res}),
    );
    runQueueCruncher();
    return await promise;
  };

// Consumes the queue.
  runQueueCruncher = async () => {
    if (_cruncherRunning) {
      return;
    }
    _cruncherRunning = true;
    while (_callQueue.length) {
      const firstCall = _callQueue[0];
      const result = await actualFunction(
        firstCall.arg1,
        firstCall.arg2,
      );
      firstCall.res(result);
     _callQueue = _callQueue.filter((f, i) => i > 0);
    }
    _cruncherRunning = false;
  };

// actual function which have to be called once.
actualFunction = (arg1: string, arg2: string) => {
  /* Implementation */
}

This way you can make sure that a single piece of code is run only once at a time. I know Javascript is single threaded, but when async is used it does not guarantee that a function is not running multiple times in parallel.

Cheers and Peace out!!!