-3

I am reading various tutorials on javascript with callbacks, but they are not clarifying a basic principle. What I understand is that when a function is called with a callback, this makes it possible to wait on execution of some code, and after that execute the callback function. So

// function definition
do_func(int num, callback)
{
   Console.log(num);
   ..
   ..
   callback();
}

//call the function
do_func(123, function(){
   Console.log("Running callback");
});

So during execution of do_func, all lines of code are executed, and then callback() is executed. However if our function changed as

    // function definition
    do_func(int num, callback)
    {
       read file...
       ..
       ..
       callback();
    }

Then the callback would be called while the file is being read. So our purpose is defeated. What is happening here?

Thanks very much!

Matt Burland
  • 44,552
  • 18
  • 99
  • 171
user2689782
  • 747
  • 14
  • 31
  • read something about `synchronous Vs Asynchronous` – Adil Shaikh Dec 09 '14 at 19:10
  • 1
    what is `read file`? How are you reading it? If it's asynchronous and takes a callback, you would have to pass your callback to it (possibly wrapped in an anonymous function). – Matt Burland Dec 09 '14 at 19:13
  • 2
    what javascript tutorial is suggesting you declare int type? – Todd Dec 09 '14 at 19:13
  • For 'int' type, I was just writing example code(I come from Java background). Read file is just pseudo code. I have been trying to read around a lot, but it can get confusing for a newbie. Answers below helped me after I have spent a couple days trying to figure it out. – user2689782 Dec 09 '14 at 19:27

3 Answers3

2

JavaScript itself is synchronous and single-threaded. You cannot write an asynchronous function.

What you can do is use some APIs provided by your environment (Node.js, Web browser) that allow you to schedule asynchronous tasks... timeouts, ajax, FileAPI to name a few.

An example using setTimeout (provided by the HTML Timing API):

window.setTimeout(function() {
    console.log("World");
}, 1000);
console.log("Hello");

What is a simple example of an asynchronous javascript function?

Community
  • 1
  • 1
Anthony
  • 107
  • 5
0
do_func(int num, callback)
{
   readFile(... , callback);
}

I'd expect that you're readFile function can also take a callback so you could just pass it along until the file has been read.

Shaded
  • 17,276
  • 8
  • 37
  • 62
0

You are correct that in your example callback() would be called right away without waiting for the file to load. In JavaScript anytime something asynchronous is encountered you can generally listen for an event to know when to run the callback function.

Example loading an image:

var img = new Image();
img.addEventListener('load', callback); //add your listener first because if you ran the next line first it might load before your listener is setup
img.src = "fileondisk.jpg";