Hugo JS

Hugo JS

1587239220

Why Promises are more flexible than Callbacks in JavaScript?

The difference between callbacks and promises in JavaScript is subtle but significant! Why exactly are we ditching callbacks in favor of promises?

How would you answer these questions in an interview??

The superiority of promises over callbacks is all about trust and control. Let me explain.

We generally need to use callbacks or promises when there is a slow process (that’s usually IO-related) that we need to perform without blocking the main program process. I once compared giving an asynchronous worker a callback function to giving a barista in a coffee shop your name to have it called when your order is ready. While this analogy captures the essence of working with an evented resource, it’s limited when it comes to understanding the problem of callbacks (which is not about their nesting nature).

Let’s try a different analogy. Let’s say you want to cook some rice and plain yogurt using a stove. Yes. You heard that right. You can cook plain yogurt and it’s extremely good when done right.

The problem is that cooking yogurt requires continuous stirring. If you stop stirring the yogurt will burn. This means that while you’re stirring the yogurt you’re blocked from doing anything else.

Moreover, when the yogurt starts boiling the recipe at that point calls for lowering the heat, adding meat broth, and then stirring some more.

If you’re the only one cooking you’ll need to do the yogurt stirring task synchronously! Your body, which is comparable to the single JavaScript thread in this analogy, is blocked for the duration of this synchronous task. You’ll have to finish the yogurt cooking before you can start on the rice. You can compare this to doing a loop in JavaScript:

putYogurtInPot()
putPotOnStove();

while (yogurtIsNotBoiling) {
  stirYogurt();
  // Now you're blocked until the loop is done
}

lowerHeat();
addMeatBroth(yogurt)

while (yogurtIsNotBoiling) {
  stirYogurt();
  // You're blocked again until the loop is done
}

turnStoveOff();

// Start on the rice

If you need to cook both the yogurt and rice simultaneously then you need to get some help. You need to delegate! You need another “thread”. You need another person.

Your son is in the house and he happens to be free to help out. Great. You call him up and ask him to do the stirring for you.

Having someone else do the stirring here is like having an external module (like Node’s fs) do the slow IO work for you. Your son in this analogy is the Node module itself.

However, to work with an async resource (with Node’s fs module methods for example) you need to use callbacks (or promises as we’ll see later). The same goes for your son. You need to give him instructions (along with the raw yogurt and meat broth). He might know how to stir but you need to tell him what to do with everything (and when to do it). You basically give him a callback of instructions and he is expected to execute these instructions at a certain point.

son.handleYogurtStirring(
  rawYogurt,
  (problem?, boilingYogurt) => {
    if (there is a problem) {
      reportIt();
    } else {
      lowerHeat();
      const yogurtMeatMix =
        addMeatBroth(boilingYogurt);
      handleYogurtStirring(yogurtMeatMix);
    }
  }
);

// Start on the rice

By doing that, you free your single-threaded body to do something else. You can cook the rice now. You are using an asynchronous API.

So what is the problem? This is all good, isn’t it?

The problem with callbacks is that you lose control of what happens to the yogurt.

Not only is the stirring process itself now controlled by your helper, but the tasks that need to be done when the yogurt gets to a boiling point are also controlled by him. There is no guarantee that he will actually perform your instructions exactly like you described them.

  • Do you trust that he’ll correctly identify the boiling point?
  • Do you trust that he’ll remember to put meat broth? Do you trust he’ll put enough and not overdo it?
  • Do you trust that he’ll remember to lower the heat?

This lack of trust is one reason why we need promises in our lives. It is why I would simply make my son “promise” to watch for the boiling point, lower the heat, and add the meat broth. I’ll also maybe make him repeat the instructions. With his verbal assurance, the yogurt cooking process becomes a promise-based one.

(async () => {
  try {
    const boilingYogurt =
      await son.handleYogurtStirringP(rawYogurt);
    son.lowerHeat();
    const yogurtMeatMix =
      son.addMeatBroth(boilingYogurt);
    const cookedYogurt =
      await son.handleYogurtStirringP(yogurtMeatMix);
  } catch(problem) {
    son.reportIt();
  }
})();

// Start on the rice

The only difference between handleYogurtStirring and this new handleYogurtStirringP is that I was promised an outcome for handleYogurtStirringP. My helper verbally assured me he will follow instructions. I have a little bit of trust added to the equation.

I used the _async/await_ syntax to consume promises here but this is not really about _async/await_ vs _then/catch_. However, you should favor the _async/await_ syntax because it has a better flow that matches the way we analyze programs. Without _async/await_ you would need to use function nesting to accomplish some tasks. Some people even call this promise hell!

Trust is great but we still do not have control. You can get some control by changing the nature of your instructions and having your son promise to notify you when the yogurt boils the first time and then you can add the meat broth to it yourself. This gives you better control but it also means that you need to be able to respond when notified, pause what you’re doing to handle the meat-broth task.

(async () => {
  try {
    const boilingYogurt =
      await son.handleYogurtStirring2(rawYogurt);
    you.lowerHeat();
    const yogurtMeatMix =
      you.addMeatBroth(boilingYogurt);
    const cookedYogurt =
      await son.handleYogurtStirring2(yogurtMeatMix);
  } catch(problem) {
    you: inspect(problem)
         && maybe(retry)
         || orderSomeTakeout();
  }
})();

// Start on the rice

The level of trust and control you get from promises depend on the library that you use. For example, let’s say you have a fancy electric cooker with a built-in stirring arm. You put raw yogurt in and you get cooked yogurt out. You can program the cooker to cook the yogurt for exactly 13.5 minutes (or whatever time is needed), and you can program it to sound an alarm if the built-in stirring arm is jammed. This cooker’s “API” is also a promise-based one because you have trust that it will either finish the process successfully or sound an alarm if something goes wrong. You have a lot of trust here!

(async() => {
  try {
    const cookedYogurt =
      await cooker.handleYogurtCooking(rawYogurt);
  } catch(problem) {
    you: inspect(problem)
         && maybe(retry)
         || orderSomeTakeout();
  }
})();

// Start on the rice

Not only that, but you also have a lot more control over this cooker. You can make sure it’s on a steady non-slip surface and that kids don’t mess with it. You can even plug it into some form of uninterruptible power supply. You have an actual promise object in this analogy. You can do things to it while it’s pending. The yogurt cooked with a cooker might not be as tasty as the one cooked on the stove but it’s certainly a more reliable outcome.

That’s really the difference between callbacks and promises. It’s not about syntax or nesting. It’s about control and trust.

Thank you for reading!

#javascript #programming #technology

What is GEEK

Buddha Community

Why Promises are more flexible than Callbacks in JavaScript?
Hugo JS

Hugo JS

1599295469

What is Callback-Function in JavaScript? How it is Replaced By Promises?

Let us understand term _Callback _by an real-world example: Suppose, you are calling to your Girlfriend (If you have) and she is busy in another call then she send message to you : “I am busy right now, Call back you later.!!”. After completing her work, she calls you back and this is what call back in JavaScript as well.

In JavaScript, When a function is executing (Girlfriend is talking with someone) then after function execution is completed another function is started for execution this is call back function.

Now you are thinking that its depend upon when, where you are calling function and all function call is “Call-back function”. Image for post

Here, _printWorld() _function is executed after _printHello() _complete its execution but this is not call-back function example because _printHello() _is not Asynchronous function. Suppose, _printHello() _prints after 1 Second then _printWorld() _executes first.

Image for post

What if we want “Hello World” output when Asynchronous function is there. We can pass function as argument and calls it after _printHello() _complete its execution. Here below code snippet of how _function pass as argument _:

Image for post

Callback function can be defined as a function passed by argument and executes when one function completes its execution.

Suppose, If you have API (Application Programming Interface) to get Students Roll numbers and select one of Roll number — getting that roll number’s data and print that data. We don’t have API to get students data so we are using _setTimeout() _Async function and getting roll number after 2s, We are also selecting one of roll number manually after 2s and print Roll number’s data after 2s. This can be done by call back function.

Image for post

The program became complex and complex if we have too many things to do like Getting Students data, Selecting one of them student, get student’s roll number and get result by roll number then it become very complex. If you have any Error in this then debugging is also tedious task, this things is called “Callback Hell”, which is shape like “Pyramid Of Doom”.

To overcome with this problem, Promises is introduced in JavaScript. Promises has three states : Pending, Resolved, Reject. Promises is created by Constructor : new Promise(). It has one executor function which has two arguments (resolve, reject).

Promise object has three methods: then(), catch() & finally().

Image for post

If Promise is successfully executed then its data is transferred through resolve function and if it has error then passed through reject function.

We have implemented same task which is done using call back function in Promises and its easily understandable However it is complicated compare to callback function but when you use promises for sometimes then it’s easy to implement.

In _getRollNumber(), _resolve method’s data is caught by then() functions arguments and reject method’s data is caught by catch() function. Here In Promises, Every task has different promises because of that it is easy to debug and readable compare to call back function. You can see that there is no shape like “Pyramid of Doom” in Promises. This is how Callback function is replaced by Promises.

Thank you for reading!

This article was originally published on Medium.com

#javascript-tips #advanced-javascript #javascript #callback-function #promises

Julie  Donnelly

Julie Donnelly

1602406920

JavaScript Promise: Methods Comparison

Introduction

Promises in JavaScript are used to handle asynchronous operations by keeping track of whether a certain event has happened. If that certain event has taken place, it determines what happens next. Promises return a value which is either a resolved value or a reason why it’s rejected. They can handle multiple asynchronous operations easily and they provide better error handling than callbacks and events.

Callback: A callback is a function that is passed into another function as an argument to be executed later.

Events: Events provide a dynamic interface to a WebPage and are connected to elements in the Document Object Model(DOM), for example: onclick(), onmouseover() etc.

A Promise has four states

Pending: Before the event has happened, the promise is in the pending state.

Settled: Once the event has happened it is then in the settled state.

Fulfilled: Action related to the promise has succeeded.

Rejected: Action related to the promise has failed.

#javascript #javascript-development #javascript-tutorial #promises #javascript-tips

Jeromy  Lowe

Jeromy Lowe

1595553079

Intro to Callback in JavaScript

During my journey of learning JavaScript and a few days in with React, I had to come to terms with callback functions. It was impossible to avoid its existence and blindly using it without understanding. To understand callback function we have to know a bit about functions. Here I want to talk about function expression, arrow function, and callback function.


What is a Callback function?

According to MDN doc:

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.

In JavaScript, functions are objects, which means, like any other objects it can be assigned to a variable and passed as an argument to another function. In a nutshell, a callback function is a function that is provided as a parameter for other methods such as forEach method or addEventListener method and gets invoked at a certain point in time.

Passing functions as arguments

So how do we do this? Let’s see with an example below:

document.addEventListener(‘click’,whoAmI);

//whoAmI Function Declaration(Function Statement)
function whoAmI(event){
  console.log(event.target.tagName)
}

We attached the ‘click’ event listener to document with whoAmI function as a parameter that logs the tag name of the clicked target. Whenever ‘click’ happens whoAmI function will be called with an _event_ argument. We call whoAmI a callback function.

When we call a function by its name followed by ( ), we are telling the function to execute its code. When we name a function or pass a function without the ( ), the function does not execute.** The callback function doesn’t execute right away. Instead, the addEventListener method executes the function when the event occurs.**

One more thing I want to mention is because we used function declaration, we were able to call thewhoAmI function before it was declared. It’s the magic of hoisting in JS. But with function expression, it doesn’t get hoisted. So the order of writing function expressions and using them as callback would be crucial.

#callback #javascript #callback-function #function #javascript-fundamental

Promise.allSettled() vs Promise.all()

Promise.allSetlled() is recently introduced in ECMA 2020.
Check out how it is different from Promise.all()

https://www.geekstutorialpoint.com/2020/05/promiseallsettled-vs-promiseall.html

#javascript #promise.all #promise.allsettled #ecma #promise #jquery

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript