simple callback pattern 1

simple callback pattern

const add = (a, b, callback) => {
  setTimeout(() => {
    callback(a + b)
  }, 2000)
}

add(2, 3, (sum) => {
  console.log(sum) // should output 5 after 2 seconds
})

Here is what the above code is Doing:
1. We’re defining a function called add that takes three arguments: a, b, and callback.
2. Inside the function, we’re using setTimeout to delay the execution of the callback function by 2 seconds.
3. We’re calling the add function and passing in 2, 3, and an anonymous function as arguments.
4. The anonymous function is the callback function that will be executed after 2 seconds.
5. The callback function is passed the sum of a and b as an argument.
6. The callback function then logs the sum to the console.

The output of the above code will be 5 after 2 seconds.

Now let’s look at a more complex example.

Similar Posts