79501784

Date: 2025-03-11 18:38:26
Score: 0.5
Natty:
Report link

I've created a NodeJS package to deal with callbacks and I want to present it as a possible solution to avoid 'callback hell'.

It allows to run functions with callback arguments in parallel or in sequence, even accessing previous results (creating cascading calls, waterfall).

An example:

/*
Creates a log file from several other files using node:fs functions with callbacks.
*/

import { CB } from "callback-utility";


const logFile: string = path.resolve(__dirname, "mainLog.log"),
      file1:   string = path.resolve(__dirname, "file1.log"),
      file2:   string = path.resolve(__dirname, "file2.log"),
      file3:   string = path.resolve(__dirname, "file3.log"),
      file4:   string = path.resolve(__dirname, "file4.log");


// Create execution structure 
const structCB = 
    CB.s ( // 🠄 sequential structure as root

        // Delete current log file
        CB.f ( fs.rm, logFile, {force: true}), // 🠄 Creates a function structure using CB.f()


        // Create log from several files
        CB.p ( // 🠄 parallel structure, since the order in which every file is written in
               //    log is not important (can be parallelized)

            CB.s ( // 🠄 sequential structure
                CB.f ( fs.readFile, file1, {encoding: 'utf-8'} ),      // 🠄 read content 
                CB.f ( fs.appendFile, strLogFile, CB.PREVIOUS_RESULT1) // 🠄 write results from 
                                                                       //    previous call to log file
            ),

            // The same (in parallel) for every file ...
            CB.s (
                CB.f ( fs.readFile, file2, {encoding: 'utf-8'} ),
                CB.f ( fs.appendFile, logFile, CB.PREVIOUS_RESULT1)
            ),
            CB.s (
                CB.f ( fs.readFile, file3, {encoding: 'utf-8'} ),
                CB.f ( fs.appendFile, logFile, CB.PREVIOUS_RESULT1)
            ),
            CB.s (
                CB.f ( fs.readFile, file4, {encoding: 'utf-8'} ),
                CB.f ( fs.appendFile, logFile, CB.PREVIOUS_RESULT1)
            )
        )
    );


// Execute and retrieve results using Promise (async/await)
const objResult = await CB.e (structCB);


// Check results
if (objResult.timeout || objResult.error)
    console.log("Something went wrong while creating the log");
else
    console.log("Log created");

In the above example, 9 functions with callbacks were invoked and ran in parallel or in sequence, accordingly to the structure created to rule the execution.

All results can be retrieved at once.

Get, please, more info about it in npmjs.com/callback-utility

There are several good options available to address this issue, and I want to present a new one. I hope it will be useful.

Reasons:
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Moacyr Catani