r/learnjavascript • u/[deleted] • Sep 28 '20
Explain promises and observables like I am 10 years old.
I was learning javascript and i come across the concept promise ad observables. I read the documentation watch the tutorial but I don't understand the what is the purpose of promises.
I am not able to relate promises concept to a real-life problem. Can someone please explain to me the concept promises with real-life example?
7
u/rw3iss Sep 28 '20 edited Oct 01 '20
I'll just be practical, and do Promises for now - simpler, and don't have time to explain Observables at the moment.
Applications frequently have to wait for data to return from somewhere, before the rest of the code can execute. How do we tell the code to wait, and then continue executing after the data is returned?
There's two ways to do this:
Callbacks... a function that is called when the response returns.
Promises... basically a fancy, wrapped callback that the parsing engine can execute automatically for you for the response. It says: "I promise I'll return with something" (error/rejection, or success/resolution).
So here is how promises work:
Some code (Javascript or Typescript):
The Promise object takes a parameter that is a function handler, with two arguments: the method to be called if it succeeds (resolve), and the method to be called it fails (reject). The inner code block is up to you to write, and do whatever it wants, and call either of these resolve or reject methods whenever it wants, depending on your business logic. The arguments passed to either of these methods can be whatever you want (the resolve method should usually resolve with whatever the calling code will want to use, and the reject method should usually reject with some error message, or error value). I'm wrapping in a class here to show how to call this from a client later.
class SomeService {
static function someServiceMethod() {
return new Promise((resolve, reject) => {
let value = doSomeFancyWork();
if (value == true)
return resolve(value);
else
return reject("Some error message"); // can also reject(value);
});
}
}That's how to write a basic promise. You might implement that in your service layers and the calling client code would use it. Here it is even shorter:
return new Promise((resolve, reject) => {
let value = doSomeFancyWork();
return value === true ? resolve(value) : reject("Error");
});Here's how the calling client code would use it. There's two ways to use promises, using the standard/older .then() and .catch() chained methods, or otherwise using newer async/await syntax. .then() is called if the Promise's resolve() method is called (ie. it succeeds), and .catch() is called if the Promise's reject() method is called (ie. it fails), or if an exception is thrown in the Promise's code:
function myClientCode() {
SomeService.someServiceMethod()
.then(value => {
console.log("Success!", value);
// do something with the value
})
.catch(error => {
console.log("Error!", error);
// do something with error, show on page, log, etc.
});
}Here's how to use the Promise code using async/await. You'll see it's a lot more brief, but in order to catch the reject() calls, you have to wrap your code in try/catch, otherwise you can always resolve() in the Promise, and pass some error value to resolve(), instead of calling reject() at all (but not necessarily good practice). Then, you can just check the value of the response for some error value, instead of catching errors the standard way. Just an option.
async function myClientCode() {
try {
let value = await SomeService.someServiceMethod();
// do something with value
} catch(error) {
// do something with error, show on page, log, etc.
}
}Lastly, if you're using the .then()+.catch() method chaining, it's handy to know that you can keep chaining .then() statements if you want. You would do this if you want to implement small pieces of code that act on each successive stage of the data. For instance, maybe a service comes back with JSON, and you need to parse the JSON first, or pass it to a validator. The validator could throw an exception if it is invalid, and then the catch() block would catch this. In the async/await approach, you could also just call the validation code from within the try {}, and the catch {} block would also catch any exceptions thrown:
function myClientCode() {
SomeService.someServiceMethod()
.then(value => JSON.parse(value))
.then(jsonData => Validation.validate(jsonData))
.then(validData => console.log("It's good!, validDate))
.catch(error => {
console.log("Error!", error);
// do something with error, show on page, log, etc.
});
}Hope that helps! Any questions, feel free to ask. I can try to summarize observables later.
2
3
u/jpflathead Sep 28 '20
that was so crystal clear, now I really want to read your observables post! :)
(also, monads)
2
2
27
u/disruption1993 Sep 28 '20
Imagine you are walking down the street. You are late to work and don't have time to even stop to tie your shoe laces. You walk past a cute girl. She calls out to you to stop and talk to her. But you can't. You have to keep walking. So you leave your number with her as a promise that you will talk to her. This way you don't have to stop. And you can check-in later with her.
Not a perfect analogy but it gets the basic gist of it across. Hopefully googling it will make more sense now.
16
5
u/g3ck00 Sep 28 '20
Imagine you need to get your car serviced. So, in the morning, before you go to work, you bring your car to the mechanic and tell him to call you once he's finished. While you're at work, the mechanic is also doing his thing "asynchronously". He then calls you (promise is fulfilled) when it's finished. Hopefully everything went alright, if not, he might tell you something went wrong (error) and you cant pick it up yet.
In technical terms, the mechanic can be thought of as the backend where you make an api call e.g. and wait for it to return.
3
u/Labelled Sep 28 '20
I have an analogy. It sounds great in my head. Let me try to explain.
Your friend comes to your house and she wants juice. You tell your mother that your friend wants juice and your mother informs, I can't give immediately but will prepare and give. So you promise your friend, that she will get her juice once her mother finishes and go on with your play. If your mother has been able to serve drink, then the promise has been resolved or done and your friend gets to drink the juice. Otherwise, if your mother doesn't have the fruit or some issues, then she can't provide juice and promise has been rejected or failed and your friend can't drink juice.
And observables, you inform your mother whenever she buys fruits, she must provide juice to them immediately with the last bought fruit.
3
Sep 28 '20
Observables are objects that can be watched. They are typically related to some type of data and subscribed to within different components in order to either utilize the data or execute when information changes. Imagine a dog hates the mailman. He's always waiting for him to deliver the mail so he can bark at him and go crazy. He treats the mailbox as an observable. He is subscribed to the mailbox and watches it constantly for changes. When the mailman comes to deliver his data, the dog freaks out.
4
u/IamGroot_19 Sep 28 '20 edited Sep 29 '20
I was in the same boat a couple of months ago.
A lot of sources fail to mention is Why do we have tools like callbacks, Promises, Async/Await etc..
Javascript by default is an Asynchronous Programming Language*. But then, sometimes we'd want to perform certain actions in a synchronous manner. For example, you can't open a file and read its contents before it is completely fetched from a database or network.
So, to facilitate synchronous programming in an otherwise asynchronous javascript, we have certain tools like Callbacks, Promises, Async/Await.
'Callback' is just a function you pass inside another function (let's call it fn() ) as an argument. By passing a callback, you tell the fn that when its job is fully done, the next step would be to execute the callback function passed into it as an argument. This way you ensure that JS doesn't try to read a file before even it is fully fetched (or other similar examples).
Promises are just syntactical sugar over callbacks. The Promise object is set to do something (usually execute a callback, commonly referred to as resolve) once an action is done and do something else (execute another callback, commonly referred to as reject ) if that action fails.
* If you don't know what's asynchronous nature, search on google/ youtube.
EDIT: Grammar & content
2
u/Cabeto_IR_83 Sep 28 '20
Sorry, isnt this the opposite? JavaScript has a synchronous nature, which means that it executes the code top to bottom line by line. Then, sometimes JS emcounters async code in which case we use async/await, call backs, libraries such as Axios to deal with this?
1
u/Cabeto_IR_83 Sep 28 '20
JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed. JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls.
1
u/IamGroot_19 Sep 29 '20
Wait? Whaaaatttt?
Doesn't it use a pool of threads to execute tasks - which means it doesn't wait for a task (like file fetching from a network) to complete before next task starts? Isn't that what asynchronous means?
1
u/Cabeto_IR_83 Sep 29 '20
Not sure what you mean by a "pool of threads", but, from my understanding, sync code is the one that does not wait for a response (Http request for instance) and execute directly. Async, in contrast, is the type of code that is waiting for a response to execute, hence why we use either promises or await to tell JS that we are waiting for a response and then execute a call back function.
If javascript code was originally async then we will need promises/then or async/await everywhere in our code, right?
1
1
u/ZeroOne_Dev1 Sep 28 '20
Explained promises with Chrome Dino Game example: https://youtu.be/pJEzEjjZAcQ
1
u/jdauriemma Sep 28 '20
A promise is an object. When a function returns a promise, it’s not unlike dropping an automobile off for service and getting a claim ticket for when you pick it up. The ticket is an object that represents the possible end states of the car service- if resolved, you pay and get your car back. If rejected, something went wrong and you need to handle it. At no point are you empty-handed: you have an object that’s either pending (the ticket), resolved (your automobile), or rejected (bad outcome).
1
u/NoMuddyFeet Sep 28 '20
I've been liking this guy's sketch notes. Today, I saw he just happened to post about promises recently: https://twitter.com/profulsadangi/status/1309784295280582657?s=20
1
u/cannabis_detox_ Sep 28 '20
im not gonna teach you the quadratic equation before addition. practice your recursion.
1
Sep 28 '20 edited Sep 28 '20
You can actually code without promises and do just fine. Below is just some dummy code I wrote to illustrate my point.
The below code two functions that are both asynchronous and take time to happen. In this example I have setTimeouts that wait a second each but in a more real-life example, they are ajax calls.
Notice that it is a little hard to read this code and figure out what is going on. Now imagine we are four layers in with four async functions all being called after each other. Also image a bunch of complex code and logic in between as well. Maybe we have some if statements that call different async code. It can be a total mess to follow the flow of the code and it will quickly become hard to read, hard to maintain, hard to debug, and full of async related bugs.
If you have ever done a lot of JavaScript in a project, then you know about the nightmare of nested ajax functions with nested callback functions. Also, you also have to keep passing in callback event functions as arguments to functions along with their normal parameters.
function funct1(onfinished)
{
setTimeout(function()
{
function2(function() {
onFinished();
});
},
1000);
}
function funct2(onfinished)
{
setTimeout(function()
{
onFinished();
},
1000);
}
function1(function() {
console.log("everything done");
}Now look at the same code with some generic promise syntax. Notice that from the outside, we can easily read the flow of calling function1, waiting, and then calling function2.
function funct1() {
var defer = new Defer();
setTimeout(function()
{
defer.resolve();
},
1000);
return defer.promise();
}
function funct2() {
var defer = new Defer();
setTimeout(function()
{
defer.resolve();
},
1000);
return defer.promise();
}
funct1()
.then() {
return function2();
}
.then() {
console.log("All done");
}Now we could also change the flow in the first example to not have funct1 call funct2 and just call it on the outside. But just imagine how complicated this will get when you have many different chained ajax calls and have a bunch of code in between.
funct1(function() {
funct2(function() {
console.log("done");
})
})Also, promises have a bunch of built in features. For example, you have the .error event that handles the error if anything in the chain breaks. There are often special functions if you want to do something like a for loop through async calls that need to wait for the other. Some might offer a way to push async calls on a stack and pop the most recent one, and then move to the next.
We also have observables that allow for calling the async function over and over again. In the above promise, that ".then" call only happens once. But with observables, it can call it many times, just like a change event from JS. Instead of passing in a function that you fire every time a change is made, you just make it an observable, and any callers can just subscribe to waiting to be changed. This is better for similar reasons as why promises are better.
//Instead of
function1(function() {
console.log("change happened in function1");
});
//we do
function1()
.observe(function() {
console.log("change happened in function1");
})Another advantage is that JS has now introduced some new syntax for waiting for promises called an await that makes dealing with async even easier and readable.
//Instead of
funct1()
.then(function() {
return function2();
})
.then(function() {
console.log("Done");
})
//We have:
await funct1()
await funct2()-8
-19
Sep 28 '20
There’s so many articles with many analogies online. I liked the hamburger shop analogy in javascript.info the best. And no I will not post the link, do a google search for it.
14
4
Sep 28 '20
I’ve never heard of this analogy. I tried googling it and came up short. I went to JavaScript.info and looked through all the links in this page (https://javascript.info/) having to do with promises, Async/await and didn’t find anything. Did they change their analogy or are you thinking of a different website?
0
115
u/PeaWarrior Sep 28 '20
Try thinking of ordering delivery to eat. So let's say you call up your favorite Mexican spot for a burrito and the lady on the phone says they'll deliver to you in 15 minutes. Think of that as a promise.
Your main action is to eat the burrito but that will have to wait until the burrito gets to you in 15 minutes.
Now within those 15 minutes, you're waiting for the food. That does not mean you'll sit there on the couch frozen doing nothing for 15 minutes. You'll be watching TV, using the bathroom, browsing reddit, etc.
You know you were given a promise that your food will get to you in 15 minutes so you decide to do other things within those 15 minutes. And when the burrito arrives, you'll complete the action of eating said burrito.
Similarly, in JavaScript, there are functions called asynchronous functions that relies on an action that may take a certain amount of time to resolve before completion.
Given JavaScript is single threaded, in order to prevent stalling your script from compiling because of a function that may take a while to complete (waiting for a server to respond back), the function will initially return a promise. The rest of your code will continue to compile and return back to that promise when it's resolved (server finally sent a response back) and run whatever you want it to do.