Home > Software engineering >  How do I make my callback function include setTimeout, accept parameters and also include error hand
How do I make my callback function include setTimeout, accept parameters and also include error hand

Time:10-30

I'm creating a callback addition function, the operation needs to have a delay using setTimeout of 100ms. I have the add function which I'm not sure how I can "import" into my addCallback:

// Validating that the input is numbers
function numbersValidation(number1, number2) {
  if (!Number.isFinite(number1) || !Number.isFinite(number2)) {
    throw new TypeError('Only numbers are allowed');
  }
}
// Add function
function add(number1, number2) {
  numbersValidation(number1, number2);
  return number1   number2;
}
// Callback function
const addCallback = (err, number1, number2, add) => {
  if (err) {
    return err;
  }
  return setTimeout(() => {
    add(number1, number2);
  },
  100);
};

I thought that with a callback I need to insert my add function as a parameter, but my IDE says that add has already been declared in the upper scope. I also should use the "error-first" callback, ergo I added the err at the beginning, but I'm not sure if it works like that or not. Can someone please pinpoint me in the right direction for the above to work? Thank you

CodePudding user response:

A callback based function should have a callback as the last parameter, and generally does not return anything:

function someFunction(arg1, arg2, callback) { ... }

Inside the function, you will call callback(error) if there is any error, or callback(null, something) is things go fine.

Putting it all together:

// Validating that the input is numbers
function numbersValidation(number1, number2) {
  if (!Number.isFinite(number1) || !Number.isFinite(number2)) {
    throw new TypeError('Only numbers are allowed');
  }
}

function add(number1, number2) {
  numbersValidation(number1, number2);
  return number1   number2;
}

const addCallback = (number1, number2, callback) => {
  setTimeout(() => {
    try {
      const result = add(number1, number2);
      callback(null, result);
    } catch(error) {
      callback(error);
    }
  }, 100);
};


addCallback(2, 3, (error, sum) => {
  if (error) {
     console.log('error summing numbers', error);
     return;
  }
  // do something with the sum
});
  • Related