Callback JavaScript

Callback JavaScript

tl;dr

What’s callback function in JavaScript ? Callback function in plain JavaScript, Asynchronous and React

So, what is callback function ?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

MDN Web Docs

Above is the definition of callback function from MDN Web Docs.

# Real life example ?

Scenario:

  1. Bob give a call to Alice.
  2. Alice isn’t pick up the call.
  3. Thus, Bob leave a message to Alice, to get back to Bob as soon as possible.
  4. Alice receive the message and give a call/message to Bob.

When Bob leave a message to Alice, we can imagine that Bob is passing a callback function and awaiting Alice responded to the callback function.

Callback function in plain JavaScript

/**
 * A function taking two params
 * @param {string} message - A string output to console
 * @param {function} reply - A function (callback function)
 */
function calls(message, reply) {
  console.log(message)
  reply()
}

/**
 * Output string to console
 */
function replyFromAlice() {
  console.log("I'm Alice, speaking please.");
}

function replyFromRobot() {
  console.log("The number you have dials is unreachable. Please leaves a message")
}

calls("May I speak to Alice ?", replyFromAlice);
// Expected from console.log
// May I speak to Alice ?
// I'm Alice, speaking please.

calls("Baby Shark Du...Du...Du...", replyFromRobot);
// Expected from console.log
// Baby Shark Du...Du...Du...
// The number you have dial is unreachable. Please leave a message

Asynchronous callback function

/**
 * Asynchronous callback function
 * Return "...\newline Hello ?" after awaiting 3seconds
 */
function asyncCalls(message) {
  return new Promise(resolve => { 
    console.log(message); 
    setTimeout(() => { 
      resolve("...\n Hello ?");
    }, 3000);
  });
}

/**
 * Asynchronous function, `then` and `catch` accessible from promise
 * resolve - will fall in `then` clause
 * reject - will fall in `catch` clause (I don't include `reject` in this post)
 */
asyncCalls("Du...Du...Du...").then(function(response) {
  // now, this is a callback function for `resolve()`
  console.log(response)
  // Expected
  // ...
  // Hello ?
}).catch(() => {})

// ES 6 - arrow function pattern(Don't be confused, both is doing the same thing)
// asyncCalls("Du...Du...Du...").then(response => {
//   console.log(response)
// }).catch(() => {})

then() clause is accepting a function as parameter. We can access the value return from resolve(value). For the case above, we are return the ...\n Hello ? in the resolve(). Hence, we can access the value in then().

Using callback in React

Pass the callback function as a props and get it fired whenever you need it.

  • Passing data from child component(s) to parent component(s)

@ Passing data from child component(s) to parent component(s)

import React from "react";

function Child(props) {
  function handleOnClick() {
    // Business logic

    const { onClickChild } = props;

    if (onClickChild) {
      // Fire the callback function to return value if needed.
      onClickChild("Demo for passing data to parent component");
    }
  }

  return <button onClick={handleOnClick}>Child</button>
}

export default function Parent() {
  function handleOnClickChild(valueFromChild) {
    console.log(valueFromChild);
    // Expected result
    // "Demo for passing data to parent" in console
  }

  return <Child onClickChild={handleOnClickChild} />;
}

On Child component, the onClick event on <button /> is accepting a callback function. Thus, we pass in a callback function handleOnClick().

Next, the onClickChild prop is another callback function for <Child /> component. It provide the functionality for parent component to retrieve the value from <Child /> or to continue action in parent component without intercept the default business logic in <Child />.

Conclusion

It’s good to know the fundamental of callback because it’s useful tools to handle asynchronous action or something you need to do-it-later.

** (Google about callback-hell. Async/await is come to rescue to prevent callback-hell (for promise) )

Thanks for reading.  😁

Comments

(0 Comments)

Your email address will not be published. Required fields are marked *