set a sequence of functions in javascript

There are different ways to set a sequence of functions in JavaScript depending on the use case. One common approach is to use callbacks or promises.

Using Callbacks:

index.tsx
function firstFunc(data, callback) {
  // do something with data
  const result = data + 1;
  // call the next function in the sequence with the result
  callback(result);
}

function secondFunc(data, callback) {
  // do something else with the data
  const result = data * 2;
  // call the next function in the sequence with the result
  callback(result);
}

function thirdFunc(data) {
  // do something else with the data
  console.log("Final result:", data);
}

// Call the functions in sequence
firstFunc(2, function(resultFromFirstFunc) {
  secondFunc(resultFromFirstFunc, function(resultFromSecondFunc) {
    thirdFunc(resultFromSecondFunc);
  });
});
658 chars
26 lines

Using Promises:

index.tsx
function firstFunc(data) {
  return new Promise(function(resolve, reject) {
    // do something with data
    const result = data + 1;
    // resolve the promise with the result
    resolve(result);
  });
}

function secondFunc(data) {
  return new Promise(function(resolve, reject) {
    // do something else with the data
    const result = data * 2;
    // resolve the promise with the result
    resolve(result);
  });
}

function thirdFunc(data) {
  // do something else with the data
  console.log("Final result:", data);
}

// Call the functions in sequence
firstFunc(2)
  .then(secondFunc)
  .then(thirdFunc)
  .catch(function(error) {
    console.error(error);
  });
676 chars
31 lines

In both examples, the functions are called in sequence and the result of each function is passed to the next one until the final result is obtained. The first example uses callbacks and the second one uses Promises, which are both common ways to handle asynchronous operations in JavaScript.

gistlibby LogSnag