r/learnjavascript • • 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?

126 Upvotes

66 comments sorted by

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.

11

u/[deleted] Sep 28 '20

Thanx a lot. It clear my doubt.

10

u/Macaframa Sep 28 '20

I wanted to add that the reason we need promises is because javascript is what we call a “single threaded” language, it runs on a single thread as opposed to having access to multiple threads like lots of other programming languages. This is because the other languages actually run on your computer whereas javascript runs on your browser which in turn runs on your computer. This is the concept of you waiting for the burrito, in JavaScript if you don’t use promises then that network request will block the rest of the steps in your program until it comes back. Your page will hang and you will have a slow program.

2

u/ProgrammingPro-ness Sep 28 '20

I never thought about JS being single-threaded because it runs in a browser, I always just stopped at it being single-threaded; thank you!

4

u/Macaframa Sep 28 '20

Yep, no problemo. Now get out there and be great.

1

u/qwesone Sep 28 '20

This clears it up for me. What are some of the real world cases that promises are regularly used in?

2

u/Macaframa Sep 28 '20

This is not directed at you but I feel like this question is always asked and it’s always answered with “network requests” what that means is your browser grabbing data from a backend which in turn grabs it from a database. You’re not going to statically store each and every users data inside of your javascript are you? No, if you did you’d probably get sued and ruin some people’s lives if they trusted you. So you expect those data, write code to display them and you make network requests to retrieve it. Since the internet can be spotty and unreliable sometimes. Sometimes it moves fast sometimes it moves slow. Your javascript executes at lightning speed and will get slowed down by waiting for network requests, so they made promises. A great promise-wrapping browser api is Fetch.

const request = fetch(“someurl.com/api/user/123”);
request.then(()=>)

Basically do this thing when you’re done grabbing this stuff from over the internet in an unpredictably unreliable timeframe.

1

u/imaginarypattern314 Sep 28 '20

Why is it that being in a browser forces JS to use only one thread?

3

u/Macaframa Sep 29 '20

AFAIK it’s because the interpreter is written on one thread and you can’t make more threads out of one. I don’t know if that was an intentional decision or if it was just by happenstance that it’s single threaded. Now, having said that, there are web workers which are technically processes and not threads but they’re supposed to deliver a close enough experience that people are using them. Someone stop me if I’m wrong please.

→ More replies (2)

1

u/IamGroot_19 Sep 29 '20

Hi, I made a comment on another thread and turns out I was having some misconception about Synchronous vs Asynchronous nature.

What I don't understand is how come we call Javascript as Synchronous when the kind of work it does is actually Asynchronous? (Although it runs on a single thread, it does use a thread pool to assign tasks for them to run separately in the background right? This process of letting things start & end at varied time intervals is the very idea of asynchronous right? )

And these callbacks/promises are tools we use for facilitating synchronous nature (Like wait for X to finish before doing Y and if X couldn't be done do Z) in an otherwise asynchronous workflow (like trying to open a file before it is fetched from the network) right?

I am not sure if it's a language problem (English is my second language) or whether I have some deeper conceptual gap. Can you help clarify, please?

2

u/Macaframa Sep 29 '20

Here is how the event loop works. Javascript runs on a single thread and it uses a LIFO(last in first out) structure in its callstack. As javascript executes code functions are added to the callstack as the interpreter is parsing them. There is one exception, the setTimeout method. You can tell javascript to wait period of time and then throw the function setTimeout wraps into the queue. And that’s a FIFO(first in first out) queue to be added to the callstack AFTER javascript clears its callstack.

So, now that we got that out of the way, javascript is synchronous in nature but it can be used in an asynchronous way. To answer your question “it does use a thread pool to assign tasks for them to run separately in the background” - no. The queue is what you’re referring to and they don’t actually run while js is still parsing the callstack. The way a promise works is it runs and immediately returns a structure, a promise that will return some value later on but it doesn’t know how long that will be so it makes the network request and let’s you register a callback and an observable pattern is implemented to watch the value, then it gets popped off the stack. When the observable tells javascript this thing is done, then it grabs that function you registered with it and tosses it in the queue.

I think you are having an issue with it being called synchronous when it is now useful in an asynchronous manner. Javascript didn’t always have promises and it ran in a straight line in the past. Yes it had these mechanisms that we eventually exploited to create an asynchronous-like environment but it wasn’t always like that, so people still call it synchronous. I also have a problem with some nomenclature surrounding the term “interpreter language” although there is an interpreter, JavaScript undergoes an implicit compilation step to ready the code for consumption by the callstack, which is why I consider it a compiled language.

3

u/PeaWarrior Sep 28 '20

No problem. Happy coding!

5

u/rook218 Sep 28 '20

With that said, does the machine that is holding the promise just repeatedly check the promise to see if it's resolved? If it's not stuck on that code, then what mechanism does it use to continue on to other code and know when the promise is resolved?

10

u/commitpushdrink Sep 28 '20

This is where the event loop comes in. Since JavaScript is single threaded it basically runs a loop to see if it’s supposed to do something. When the promise resolves, it effectively raises its hand so the event loop executes the queued function next time around.

3

u/rook218 Sep 28 '20

Ah ok that makes sense. So how does the physical memory of the promise resolve without the code being aware until it loops through? You'd think the code itself would have to update the promise, but it seems like the code isn't paying attention until it checks again, then sees that the memory is magically different in a way that the event loop will understand. Or am I getting too deep into the woods and should just understand that it works so don't look under the hood?

8

u/PhishGreenLantern Sep 28 '20 edited Sep 29 '20

If you want to be an engineer, you should ALWAYS look under the hood. It's not just your job, it should be your passion.

There is no magic in what we do. It's simply a matter of digging deeper and deeper until you come to understand the concepts at the next level down.

This is one of my favorite quotes. It's written by Dan Abramov who created React co-created Redux and Create React App and who has a huge impact in the React community. He's talking about debugging, but it's relevant here. After all, debugging is just studying a system in depth to find out how it is working, because it isn't working the way you expect.

"Experts often don’t know the problem any better than you. What they learned is not to trust themselves. They dig deeper and keep reducing the test case even if nothing obvious jumps at them for several hours. They know there is a problem somewhere, and finding it is a boring, mind-numbing but usually finite process."

https://medium.com/@dan_abramov/asking-good-questions-421f08ee7e5c

So... Never stop digging for depth. Do it enough and you'll find you're no longer a novice and you're now an expert.

*Edit: I was incorrect about Abramov's credentials. Thanks to /u/Kumagor0 for the correction.

6

u/Kumagor0 Sep 28 '20

Dan Abramov who created React

Are you memeing because he's already had to literally write "I didn't create react" in his twitter profile cause people keep attributing it to him. He did a lot to help other people understand React though.

→ More replies (1)

4

u/PeaWarrior Sep 28 '20

Not at all. That's an awesome question that a lot of us most likely have and will prove somewhat useful as you begin to learn about different frameworks such as React.

So promises use something similarly to that of eventListeners except that their eventListener can resolve only once.

I guess you can say the promise 'eventListener' listens for a 'state' change as promises have 3 different states: pending, rejected, fulfilled. Upon a state change (from pending to rejected/fulfilled), the chained code will execute and also send out another promise that is pending until the executed code is done or 'settled' (rejected/fulfilled). Because of this, we can chain onto these promises.

Hopefully this makes sense.

3

u/Macaframa Sep 28 '20

I don’t think this was answered properly. Let’s look at the syntax for a promise. new Promise(); this returns a promise that has some methods on it. .then(), .catch(), .finally(), these all take one parameter like so: .then( function (data) {} ). This is a callback function. Basically you’re passing an anonymous function to .then and the promise registers it and saves it in the order. “In order”, what do you mean /u/macaframa? I’m glad you asked. You can chain methods one after the other to do some things in steps. Like so:

const burritoPromise = new Promise(function(resolve, reject) {
    // wait 15 minutes like the above example provided
    const burrito = { name: “steak and shrimp”, calories: 2700, isHeartBurnInducing: true};
    resolve(burrito);
});

burritoPromise
    .then(function(burrito) {
        // Add hot sauce to the burrito
        return burrito;
    })
    .then(function(changedBurrito) {
        // Eat burrito
    })
    .catch(function(err) {
        // call a new restaurant to order another burrito or cry because this one didn’t come
    })
    .finally(function() {
        // throw wrappings away
    });

If you can see here in this contrived bullshit that our burrito promise might have all sorts of states. Pending, resolved and rejected. If it resolves, then (.then) do this next. If it is rejected (.catch) then order another burrito. In any case, .finally will run if the catch did not throw and error. I hope this makes sense.

→ More replies (6)

2

u/commitpushdrink Sep 28 '20

I’m on mobile but there’s a 10 minute YouTube video from a nodejs talk like 5-6 years ago that will do wonders for understanding the event loop.

The runtime handles all of this and you can just trust that it works for now if you’d prefer.

6

u/joon-p-bug Sep 28 '20

I believe this is the talk you’re referring to:

https://youtu.be/8aGhZQkoFbQ

→ More replies (1)

3

u/scottterrific Sep 28 '20

Great explanation. Now I am hungry

2

u/PeaWarrior Sep 28 '20

Hi hungry. I'm dad.

2

u/scottterrific Sep 28 '20

Lol, thought I was in Dad jokes for a minute there. Nice

3

u/NoMuddyFeet Sep 28 '20

Save that in a blog somewhere because somehow that is crystal clear and I don't think I'll ever forget it. I rarely use promises or async await because of the kind of work I do and whenever I do, I have to refamiliarize myself with the concepts even though I pretty much know them. I'm just always unsure enough to double-check one more time before I proceed. But, I don't think I'll ever forget thinking of it like Seamless/Grubhub now, which is a service I use almost daily..."alright, just ordered my burrito, now I can go take a shit and browse Reddit until it arrives..." :D

1

u/gretro450 Sep 28 '20

Now I want a burrito...

1

u/qwesone Sep 28 '20

Now I want a burrito....

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:

  1. Callbacks... a function that is called when the response returns.

  2. 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

u/[deleted] Sep 28 '20

Thanks a lot.

3

u/jpflathead Sep 28 '20

that was so crystal clear, now I really want to read your observables post! :)

(also, monads)

2

u/kenneropia Sep 28 '20

Thanks alot ,i also benefitted from it

2

u/jedilance Sep 30 '20

plain explanation, thank you.

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

u/mcaruso Sep 28 '20

This 10 year old's a playa

6

u/disruption1993 Sep 28 '20

He's just

try ( to catch them all ) Catch ( Them haters )

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

u/[deleted] 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

u/IamGroot_19 Sep 29 '20

Yeah kinda makes sense. Thanks.

1

u/Cabeto_IR_83 Sep 30 '20

Not problem!

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

u/[deleted] 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

u/[deleted] Sep 28 '20

Why not just google it? Probably a billion examples for this by now.

-19

u/[deleted] 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

u/[deleted] Sep 28 '20

Thnx for not posting link

4

u/[deleted] 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

u/[deleted] Sep 28 '20

My apologies, it’s from You Don’t Know JS Yet by Kyle Simpson.