0
1.const geoCode = (address, callback)=> {

setTimeout(()=> {
 const data ={
    longitude: 0,
    latitude: 0
}
  callback(data)
  }) 

}

geoCode('John', (data)=>{
 console.log(data)
 })


2. const forecast =(longitude, latitude, callback) =>{

   const url = `https://api.openweathermap.org/data/2.5/weather? 
   lat=${latitude}&lon=${longitude}&appid=ff894a55e90b66e3d6cd4b2bd8ea6509`
   console.log(url);

   request({url, json:true}, (error, {body})=>{
   if(error) {
      callback('Unable to connect to the Internet', undefined)
   } else if(body.error){
      callback('Please try again', undefined)
   } else {
      callback(undefined,body.main)
      
   }

})
}

Hi, I am new to Node.js and having a hard time understanding callbacks,callback queues and how it is processed. My question is what kind of callbacks goes to the callback queue in Node? Does it have to be callback that is inside of node specific APIS,npm packages and web APIs like setTimeOut,request(), to be added inside of callback queue to be executed after the main call stack is empty? or any kind of callbacks goes into the callback queue in node.js?

Milan Poudel
  • 116
  • 1
  • 9
  • Keep in mind callback and callback queue are two separate things and they do not have any particular relationship. – SMAKSS Jun 28 '20 at 06:03
  • So what does end up getting inside of callback queue to be processed after main call stack is empty? is it even driven callbacks ? – Milan Poudel Jun 28 '20 at 06:08
  • Check this [post](https://stackoverflow.com/questions/21607692/understanding-the-event-loop) out, this may help you in understating this. If you didn't get that so far let me know. – SMAKSS Jun 28 '20 at 06:53
  • Yes but what I didn't understand still is yes setTimeOut is an asynchronous function that will be executed after sometimes so it has event as well as callback associated with it which gets added to the event queue and callback queue....Apart from all this, does all npm packages like request(), do they all go to the callback queue? I am still confused with what kind of callbacks actually goes to the callback queue to be processed later.....Is it only event driven callbacks such as of setTimeOut(callback,duration) and npm packages such as request() that gets added to the callback queue ? – Milan Poudel Jun 28 '20 at 09:24
  • 1
    Actually, as far as I know, every action under [web API](https://developer.mozilla.org/en-US/docs/Web/API) will be added to the callback queue, to run whenever the [call stack](https://developer.mozilla.org/en-US/docs/Glossary/Call_stack) gets emptied. – SMAKSS Jun 28 '20 at 09:33
  • @SMAKSS-Yes understood a lot...I will look more into to understand even better........Thank you so much! – Milan Poudel Jun 28 '20 at 09:39

1 Answers1

2

Any event-driven item in node.js ultimately has some code that inserts a callback in the event queue at some future time. This can be the built-in items like setTimeout(), setInterval(), networking through the net module, asynchronous file I/O through the fs module, etc... or it can be also be native code add-ons using the add-on API, triggering events and causing callbacks to be inserted into the event queue. This is the crux of how any asynchronous event that occurs sometime in the future works in node.js. Every asynchronous operation uses this same mechanism.

The event loop is actually fairly complex and contains a bunch of different types of queues. There's one for I/O, there's one for timers, there's one for promises. They have different priorities and a certain ordering. Promises, for example, have a higher priority than other types of events. Timers actually work a bit differently than the others, but you can still logically think of them as a set of timers that, when triggered, they cause a callback to get called.

Except for timers, when an event wants to be triggered, some native code somewhere inserts a callback into the appropriate part of the event queue. When the event loop gets around to that particular type of event, it will call the callback associated with that event and execute the Javascript associated with that callback. When that callback returns, it continues with its march around the event loop looking for other events to run the callback for. If nothing is found that's ready to go, it sleeps until something is inserted into the event queue or until the next timer is ready to fire.

Timers use a sorted linked list with the next timer at the front of the list. The event loop just compares the current system time with the firing time for the timer at the front of the list. If it's time (or past the timer) for that event to fire when the event loop gets around to checking timers, then the callback associated with that timer is executed and it's removed from the linked list. If not, the event loop moves on to the other types of events.

jfriend00
  • 580,699
  • 78
  • 809
  • 825
  • does the request({....},()=>{}) one in the second example also gets added inside the event queue and into the callback ? – Milan Poudel Jun 28 '20 at 09:15
  • @MilanPoudel - `request()` makes an http request internally which makes a TCP connection which uses native code to do networking. Responses from native code networking trigger callbacks via the event loop. But, the callbacks in the event loop in this case are at the lowest TCP level only. The callbacks at the higher level (such as the callback you pass to `request()` are just Javascript functions that get called as the http library processes the results it gets from the TCP socket. So, the HTTP response is initially triggered by an event loop event at the TCP level. – jfriend00 Jun 28 '20 at 09:22
  • @MilanPoudel - Several other callbacks are built on top of that, but they are just regular Javascript. The native code TCP support inside of node.js, inserts an event in the event queue when the http response arrives back. That triggers a callback into the Net library which is being used by the http library which is being used by the request library. When the request library finally gets its data, it calls the callback you passed to the `request()` call. – jfriend00 Jun 28 '20 at 09:23
  • @MilanPoudel - The callbacks that go through the event queue are only the lowest level callbacks that are triggered directly by native code events. Other things that use callbacks such as the `http` library or the `request()` library are based on lower level things and are getting their notifications from those lower level implementations which get theirs from native code events in the event loop. But, when those higher level things decide to call a callback to notify their caller of something, they just use normal Javascript function calls to call their callbacks. – jfriend00 Jun 28 '20 at 09:31
  • @jfriend00- Actually helped me to understand a lot. I will look deeper to understand overall. Thank you so much! – Milan Poudel Jun 28 '20 at 09:38