It's even worse than it appears.
Wednesday March 24, 2021; 12:32 PM EDT
  • I looked around for a decent explanation of JavaScript callbacks, but they take too long to get to the point, or they never explain what they are. Maybe it's too hard to explain? I've been writing a lot of docs lately, so let me try! :-)#
  • Callbacks are used when an operation is going to take a long time and your program wants to do other things while it's waiting. So you create a function to run when the operation is done, and provide that function to the slow operation you're calling with the intent that it will call this function when it's done. Thus it is a callback function. #
  • An example:#
    • fs.readFile ("notes.txt", function (err, filetext) {#
      • if (err) {#
        • console.log (err.message);#
        • }#
      • else {#
        • console.log ("The file contains " + filetext.length + " characters.");#
        • }#
      • });#
    • console.log ("Hi mom!")#
  • If you look in the console, you'll see:#
    • Hi mom!#
    • The file contains 28 characters.#
    •  #
  • An example of a real world callback. #
  • After you upload a video to Facebook, you'll get a dialog when the upload is done saying this is going to take a bit of time to process, so we'll let you know when it's done. In the meantime you can read stuff. When the video is ready, you get a message saying you can watch the video now. That's the basic flow of a callback. #

© copyright 1994-2021 Dave Winer.

Last update: Wednesday March 24, 2021; 12:51 PM EDT.

You know those obnoxious sites that pop up dialogs when they think you're about to leave, asking you to subscribe to their email newsletter? Well that won't do for Scripting News readers who are a discerning lot, very loyal, but that wouldn't last long if I did rude stuff like that. So here I am at the bottom of the page quietly encouraging you to sign up for the nightly email. It's got everything from the previous day on Scripting, plus the contents of the linkblog and who knows what else we'll get in there. People really love it. I wish I had done it sooner. And every email has an unsub link so if you want to get out, you can, easily -- no questions asked, and no follow-ups. Go ahead and do it, you won't be sorry! :-)