Asynchronous Programming - Reading Assignment

1. What is the difference between synchronous and asynchronous functions?

Hello sir, did you forgot to type the answer?

If you have any doubt, please let us know so we can help you! :slight_smile:

Carlos Z.

1. What is the difference between synchronous and asynchronous functions?
  • Synchronous functions are executed in series. The next line of code after a synchronous function call does not get executed until the function has finished executing from start to finish- the rest of the application has to “wait” for it.
  • Asynchronous function calls are executed in parallel. The function call executes in a separate thread, meanwhile execution continues on the main thread without waiting for the function to finish. Both threads execute simultaneously.
2. What is callback hell?

When multiple callbacks produce a deeply nested mess of code. This is also known as a “Christmas Tree” effect.

3. Which technique can help us solve callback hell?
  • Promises allow you to chain callbacks together instead of nesting them
  • You can also use the async and await keywords. These enable a more synchronous programming style similar to the futures/fibers mentioned in the article.
1 Like

1. What is the difference between synchronous and asynchronous functions? Synchronous functions are executed sequentially. Each statement has to wait for the previous statement to finish running in order for it to start executing. Whereas asynchronous code doesn’t have to wait for the previous statement to finish running.

2. What is callback hell? It consists of multiple nested callbacks which makes code hard to read and debug.

3. Which technique can help us solve callback hell? One of the best ways to reduce code clutter is by maintaining better separation of code. If you declare a callback function beforehand and call it later, you’ll avoid the deeply nested structures that make callback hell so difficult to work with.

1 Like
1. What is the difference between synchronous and asynchronous functions?

Synchronous or blocking means that JS can only handle process one event "single-threaded" at a time.  Whereas a synchronous task will occupy a JS task continuously until its completion, an asynchronous task can be initiated and then put aside until a later date while the JS gets started on the next task on its to-do list "event loop". 

2. What is callback hell?

Callback hell involves more complex operations that tend to produce even more levels and sub-levels of nested functions.

3. Which technique can help us solve callback hell?

Promises use a common pattern to deal with excessive callbacks in the browser.  jQuery ships with a simple built-in promise library that enables us to chain callbacks and deal with errors.  But in Node.js, a different approach is used.  By extending the runtime, you subtract away the asynchronicity and write code that looks synchronous.
1 Like

Two or more things are synchronous when they happen at the same time (in sync), and asynchronous when they don’t (not in sync).

Callback hell is a phenomenon where multiple callbacks are nested after each other. It can happen when you do an asynchronous activity that’s dependent on a previous asynchronous activity. These nested callbacks make code much harder to read.

This is the callback hell.
fs.readdir(source, function (err, files) {
  if (err) {
    console.log('Error finding files: ' + err)
  } else {
    files.forEach(function (filename, fileIndex) {
      console.log(filename)
      gm(source + filename).size(function (err, values) {
        if (err) {
          console.log('Error identifying file size: ' + err)
        } else {
          console.log(filename + ' : ' + values)
          aspect = (values.width / values.height)
          widths.forEach(function (width, widthIndex) {
            height = Math.round(width / aspect)
            console.log('resizing ' + filename + 'to ' + height + 'x' + height)
            this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(err) {
              if (err) console.log('Error writing file: ' + err)
            })
          }.bind(this))
        }
      })
    })
  }
})

Each function gets an argument which is another function that is called with a parameter that is the response of the previous action.

As we can see, this code is hard to understand and maintain, and it isn’t scalable. This is what we call callback hell.
Also known as “The Pyramid of Doom”. :laughing:

Write comments

Some callback hell’s are simple to understand. We can read it. It just… doesn’t look nice. In these cases the comments are can be very useful.

Split functions into smaller functions

Break the callback functions into smaller pieces to reduce the amount of nested code.

Using Promises

Promises are a way to write async code that still appears as though it is executing in a top-down way, and handles more types of errors due to encouraged use of try/catch style error handling.

Using Async/await

They will make your code much cleaner and easier to maintain. Declaring a function as async will ensure that it always returns a Promise so you don’t have to worry about that anymore.

Why should you start using the JavaScript async function today?

  1. The resulting code is much cleaner.
  2. Error handling is much simpler and it relies on try / catch just like in any other synchronous code.
  3. Debugging is much simpler. Setting a breakpoint inside a .then block will not move to the next .then because it only steps through synchronous code. But, you can step through await calls as if they were synchronous calls.
1 Like

Excellent answer sir! really well documented! keep it like that please! :muscle:

Carlos Z.

1 Like

1 Synchronous functions are executed by Javascript in the order in which they are arranged in the code (from top to bottom) and asynchronous functions are executed only when some programmed condition is reached.

2 Callback hell is an expression designed to indicate the existence of too many nested asynchronous functions. Call back hell, or pyramid of doom, makes reading code and debugging difficult.

3 Promises and Generators are the two techniques to solve the callback hell, they can be used separately or together.

1 Like
  1. Synchronous functions require JavaScript’s full attention until it’s completed, while asynchronous functions can be left uncompleted while JavaScript handles other functions.

  2. Callback hell: when several functions are nested, waiting for one another, to execute simple tasks. Difficult to analyze and debug.

  3. Use promises. jQuery has a promise library, for instance.

1 Like
  1. In the synchronous function, the browser will complete the execution of the said function before proceeding further. However in the asynchronous function, the function can be executed, and while the browser waits for a response it can execute other functions. It will not have to wait till the end of the function.
  2. When we have too many callbacks in multiple sub-levels is called callback hell. It makes the coding difficult to write and test.
  3. Callback hell can be solved by using promises in jQuery or Fibers in Node.js.
1 Like
  1. In Synchronous functions, an event handler will not execute until the one prior to it is completed, no matter how long this takes. Asynchronous functions initiate an event handler and can be be put aside until the response is ready.
  2. Multiple levels of nested functions particularly as code becomes more complex.
  3. Promises in jQuery. Fibers in Node.js
1 Like
  1. What is the difference between synchronous and asynchronous functions?
    Synchronous functions run sequentially top to bottom. Asynchronous function can jump around allowing them to be initiated and put aside

  2. What is callback hell?
    Problem caused by extensive nested functions - these sublevels make it difficult to track the order code executes in.

  3. Which technique can help us solve callback hell?
    formalizing functions with names and using error handling

1 Like
  1. What is the difference between synchronous and asynchronous functions?
    Synchronous functions occupy all JS attention and it moves to the next code only after completion. Asynchronous might be initiated and put aside while JS works through other tasks until the initiated one is completed
  2. What is callback hell?
    Complex operations with many levels and sub-levels
  3. Which technique can help us solve callback hell?
    We can use promises
1 Like
  1. Asynchronous functions executes codes more codes at the same time whereas synchronous programming runs codes continuously until their intended completion.

  2. More complex operations tend to produce even more levels and sub-levels of nested functions which slows down or virtually blocks the overall functionality.

  3. Using so-called promises. jQuery ships with a simple built-in promise library that enables us to chain callbacks and deal with errors.
    We could also different promise libraries such as the Fibers package which simulates synchronicity and allows us not to lock the whole server during a timed-out function for example.

1 Like
  1. What is the difference between synchronous and asynchronous functions? Since JS code is single threaded, One requested task needs to be completed before the next on can be initiated. This is Synchronous. An Asynchronous function can be initiated and set aside to a later time or date while another task can then be initiated without waiting for the first task to be completed. Ajax is usually the asynchronous code used in a browser.
    2.What is callback hell? Multiple levels and sub-levels of operations such as calling API’s, executing operations, reading and writing files, etc.
    3.Which technique can help us solve callback hell? In a browser JQuery comes with something called Promises that enables call backs to be chained and errors to be corrected. In Node.js code that looks synchronous can extend run time. Meteor does this behind the scenes in the Fiber package. The easiest way to use Fiber is via the Future sub-library. This is how it would look:
    var app = require(‘express’)();
    var Fiber = require(‘fibers’)
    var Future = require(‘fibers/future’)

// a function that “synchronously” waits for X ms var wait = function(ms) {
var future = new Future;
setTimeout(function() {
future.return();
}, ms);
return future.wait();
}
app.get(’/hello’, function() {
Fiber(function() {
console.log(‘waiting’);
wait(10000);
console.log(‘done’)
}).run(); });
var server = app.listen(3000);

1 Like

Excellent answer sir! really well documented! keep it like that please! :muscle:

Remember you can use the “Preformatted Text” Button to encapsulate any kind of code you want to show.


I am a happy Preformatted Text box, please use me wisely!

Hope you find this useful! :slight_smile:

Carlos Z.

Thank you Thecil!

I didn’t know about the code format button,
I’ll try it next time! :slight_smile::+1:

Vicki

2 Likes
  1. Synchronous functions are waiting for them to be completed, where asynchronous functions will allow for other tasks to be executed while waiting for the operation to finish.

  2. Callback hell is when some functions produce levels and sub-levels of nested functions to execute the operation.

  3. Promise library in jQuery can chain callbacks and deal with errors that way solving callback hell.

1 Like
  1. Synchronous functions all happen according to the linear flow of the code. Asynchronous functions can operate in the background while completing their tasks.

  2. Callback hell is when you have nested asynchronous functions all doing their own jobs and waiting for data.

  3. The promises tool in jQuery helps to solve callback hell.

1 Like

1. What is the difference between synchronous and asynchronous functions?
Synchronous: These types of tasks execute until they complete, not allowing for other code to run.

Asynchronous: These tasks allow other code to run once they have started.

2. What is callback hell?
Callback hell is used to describe when a function is used to call another function, and so on and so on. The code becomes very complex with multiple layers, becoming unruly.

3. Which technique can help us solve callback hell?
Using libraries like jQuery with promises can help solve and reduce callback hell.

1 Like
  1. Synchronous functions take place one after the other, operating in a single-threaded manner. Asynchronous functions depart from this thread when called (to wait for data from a server for example) and runs on a separate background thread until its completion.
  2. Callback hell is a poetic description of complicated code involving many levels and sublevels of nexted functions.
  3. Promises help us negotiate callback hell by forming callback chains and dealing with errors.
1 Like