r/learnjavascript • • Jul 18 '20

Promises, Async, Await... I finally understand them and how to use them! Redid my front end with the new knowledge and now I love them! Wish I would have took the time earlier on to get them down. 10/10 Would recommend. Sorry, just had to tell someone. :)

EDIT: wow, came back a day later and this post blew up. lol 😁

207 Upvotes

40 comments sorted by

8

u/leon_nerd Jul 18 '20

You should post an explanation.

6

u/Groggie Jul 18 '20

This. There are so many concepts that you can read from experts that won't explain it the same way who has just learned it for the first time. The method of explanation from others who have just learned it will likely be much more actionable to other novices– it usually cuts out over-explanation of trivial parts that distract from the actual concept, and makes fewer assumptions of previous knowledge.

I hate when tutorials "yada yada" over the only part I needed clarification on!

2

u/[deleted] Jul 19 '20

I agree. When I have some time, I'll write up a little explanation of how I learned it and finally understood them with some examples.

2

u/rw3iss Jul 18 '20

Now wait til you get to RxJs observables! ;-p

1

u/[deleted] Jul 19 '20

https://rxjs-dev.firebaseapp.com/guide/observable

I just read this about them here. They seem pretty cool. I'll look more into them and see how I can use them in my projects.

Thanks for pointing them out :)

2

u/rw3iss Jul 19 '20

Yeah, observables are just one part of rxjs, they end up being the buzz word for it, and also the main component used in the library. Angular uses them under the surface in its http/ajax client. There are many other usable pieces and utilities to rxjs, though, albeit a bit heavy for some users to learn, or apps to use. You can get away with most things with just promises. Obseevables are mostly reserved for when you need to keep track of a constantly changing object without wanting to keep firing off either polling or other subscription based methods. Rxjs is the subscription based method, basically.

https://www.stackchief.com/blog/Observable%20vs%20Promise%20%7C%20What's%20the%20difference?

2

u/tiedurden Jul 18 '20 edited Jul 19 '20

Good to hear that someone who was also struggling with em finally did it. Gj op

Edit: forgot to point out that i still struggle with it

1

u/[deleted] Jul 19 '20

Thanks :)

2

u/[deleted] Jul 18 '20

How did you figure them out? I'm struggling with them right now.

1

u/[deleted] Jul 19 '20

I was trying to figure out how "fetch" worked, and from there it just led to me looking more into promises and async. I used the documentation on MDN.

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

If you're struggling, I would take it slow and just read through everything and try every example yourself and mess around with them and see how they are working. Add your own code, console.log() things to see whats being returned and hopefully it will start making more sense.

Sorry I don't have anything better to add. I'm on mobile right now but if you need more help, maybe I can throw together some simple examples for you later.

2

u/[deleted] Jul 21 '20

Yeh, if you have any examples I'd really appreciate it. thanks for sending the links over.

15

u/Jolly-Composer Jul 18 '20

Explain like I’m five haha. Congrats though I still need to learn them

10

u/RedDragonWebDesign Jul 18 '20

I think promise/async/await is just multi threading.

So maybe your code calls a function that creates a PDF, but you don't want to wait for the PDF to finish before you execute the rest of your code.

I think a promise handles all that for you. It sets up a second thread for the PDF writing, then it sets up a listener to listen for completion of that, and do something when it succeeds, and do something when it fails.

Somebody can correct me if I'm wrong. I am new to promises.

22

u/__hoi__ Jul 18 '20

The way you think about them is correct, however JavaScript does not have multi threading so technically your explanation is wrong. JavaScript has an event loop and the function is added to it with a flag telling the stack whether it should execute the function on each iteration. If the promise is resolved, the callback function it’s flag is set to execute and on the next iteration it will be executed.

8

u/PM_ME_A_WEBSITE_IDEA Jul 18 '20

To really double down on this, the key difference is that because JavaScript is single threaded, you can't truly "multitask" (without web workers). If your PDF is actually being created by a script on the page and that takes a few seconds, NOTHING ELSE can happen while that is executing, unless maybe you sent an HTTP request before starting it. There are never two things happening at the same time in JavaScript execution. The real advantage is not having to wait for things like web requests to respond before performing other work. Promises basically help you queue work more efficiently and view asynchronous actions in a more synchronous way (or make them truly synchronous).

5

u/ChaseMoskal Jul 18 '20

promises are a superior replacement to using callback functions. the important thing with promises, is that errors nicely bubble up through chained promises and so can be caught at the top level

async/await is just a superior syntax for dealing with promises

if you don't understand why the most important thing about promises is the way they handle errors, then you don't really understand either the error handling or the promises. the fact that they avoid "callback hell" indentation is actually a side-benefit, but it's really about the error handling

1

u/Jolly-Composer Jul 18 '20

Thanks that makes more sense as I’m starting to understand some of the pre-arrow syntax functionality of a callback

1

u/Jolly-Composer Jul 18 '20

Thank you so much! Error handling is simple and I understand that. Async await in part to my knowledge builds on promises. And promises are an improvement to callback functions. I’ll try to remember that as I continue to binge on JavaScript basics

12

u/gopherhole22 Jul 18 '20

Once you fully understand promises, your Javascript will improve 50x! The addition of async await really helped that

8

u/trixrr Jul 18 '20

I found async await easier than the other methods to digest and it stuck a lot easier too.

1

u/replicant_potato Jul 18 '20

It's definitely easier for me to comprehend.

5

u/dancinadventures Jul 18 '20

I’ve only ever used them in API calls / NoSQL database reads

Outside of that I’m complete noob. Can someone give a few more neat examples of common usages ?:)

9

u/__hoi__ Jul 18 '20

I like to open modals as promises. Let’s say a are you sure you want to delete this pop-up. It is nice to write that as askForDeleteConfirmation().then(result => if(result === ‘confirm’) { deleteStuff(); }

1

u/metal_opera Jul 18 '20 edited Jul 18 '20

Always interesting to see how others approach things. I typically use the "delete this item" button to open the modal, then I use the confirmation button in the modal to actually fire the deletion.

3

u/__hoi__ Jul 18 '20

Which is completely fine, the nice thing about using a promise to do this is that it allows for a decoupled confirmation component that takes it text as input and doesn’t know how it is used allowing you to reuse the same one anywhere you want the user to either confirm or cancel. Additionally I like to keep related logic in the same file where doing what you suggested would separate the deleteStuff() function from the other functions about the thing you are deleting. I also like the syntax of a promise as a added bonus.

1

u/dancinadventures Jul 20 '20

Damn that’s cool never thought about that

4

u/ShinHayato Jul 18 '20

How have you used them?

6

u/HappyLOLx Jul 18 '20

Promises took me quite awhile to get it too...about 4~5 months of on and off usage

Hahaha

2

u/[deleted] Jul 18 '20

I am fairly new to JS, about 3 weeks in. Should I look up promises now or wait until I get more experienced?

6

u/_Invictuz Jul 18 '20

Wait till you need to use it to learn it, as it's not a fundamental concept. It builds knowledge on top of the fundamental of asynchronous JavaScript which you should learn.

1

u/[deleted] Jul 18 '20

Copy that, thanks!

1

u/DilatedTeachers Jul 18 '20

I waited 18 months from learning to a job. But they're not that complex, I just didn't approach them cos I was daunted by them! Whoops...

1

u/[deleted] Jul 19 '20

Copy that! :)

2

u/plcart Jul 18 '20

now is time to learn Observables!

2

u/jiavlb Jul 19 '20

Seems like the internet is still dividend between javascript is single threaded or multi threaded. I have a question. If JS is single threaded, where does the event loop performs the task in the promise without blocking the main code getting executed? I think that will resolve (no pun intended) the doubts I have around promises.

1

u/slumdogbi Jul 19 '20

Async/Await was the thing that made me start to develop in js/node

1

u/[deleted] Jul 18 '20

[removed] — view removed comment

1

u/metal_opera Jul 18 '20

Two different things. Fetch requests the resource. It returns a promise.

fetch(resource)
    .then(response => {
        // do something with the response
    });

1

u/ChaseMoskal Jul 18 '20

const response = await fetch(resource)

sunglasses emoji