You just don't give a basic example of the usage of asyc/await, you give how to use them in multiple calls scenarios. Great work!!! And thank you for sharing!
I'm glad there a lot of people disagreeing with you. Your video is nice and well explained, but I got to say I prefer ".then" over "async/await". I simply found it way easier to understand. It's closer to how a human would think about something asynchronous. "do this and when you will have the data, then do that." when I was learning JavaScript, the async/await was bugging me and what made me understand it was the "then"
I agree. Seems like a lot of (relatively) newer JavaScript improvements are making it possible to write more lean and compact code, but that doesn't necessarily make it more (human) readable. One could argue it could be due to lack of familiarity, but for me personally, I'd use that argument for learning a new framework/toolkit/API/SDK over an evolving language. I see other languages improving over time, but a lot of changes that were made to JavaScript introduced a lot of inconsistencies IMHO. The changes introduced a lot more "ways to skin a cat" instead of focusing on readability and a single "best/right way" to do things.
I have a 300 lines long test and async/await cut execution time from 14 sec to 4. Who cares about human undertanding? Its not for regular bread buyer. You learn it in a day and benefit for life. '.then' is slowwww
I must say I still think working with Promises is a lot more clean than working with async/await. With async/await, you end up with a lot more LOC's, you still have to deal with a promise if values are returned from the async function, or you have to use top-level async/await, which is ultimately undesirable since asynchronous code can lead to frustrating long debugging when not applied correctly in respect to synchronous code.
I finally got the idea of async in JS, up to this moment I struggled with understanding sequences of actions when running async code. Now I understand it completely, thanks James!
async/await being syntactically "cleaner" is pretty well a value judgement. There are some real advantages to async/await though, chiefly (1) an asyncFunction is guaranteed to throw by way of returning a rejected promise (or rejecting its returned promise), even from a sync code fail ... the advantage accrues in the caller (2) .then().then() related scope issues disappear ... remember all those "how do I access previous results?" questions in StackOverflow?
I definitely agree on the "cleaner" part, the example from this video is a lot cleaner in the .then syntax IMO. It can also be a lot shorter than the async await version, since it could easily be on 4 lines without losing any clarity. Even though the async await version is a lot more verbose, it's a lot messier than the .then version.
Honestly, the promise.all example was really ugly. I'd rather just do: let urls=[....... ] return Promise.all( urls.map( url => fetch(url).then(res=>res.json()) ) ) This is so much cleaner than the example in the vid
They both have their place. Promises are cleaner for pipeline type stuff, particularly if you can go point-free: fetch(url) .then(res => res.json()) .then(console.log) .then(console.error) It's often a more concise syntax, (reduce lines of code by 30%) so can be great for testing also. Also less cognitive load. Async await has its place, especially for writing big chunks of procedural code where you really need space to work in. Also it's easier to debug.
One other thing to probably be weary of, if you have too many await statements or long chained promises and then succeed them by some logic that is not directly related to the response they generate, you would potentially block JS from rendering the UI. Its important to put all your awaits only within an async function scope and not do anything else in there.
..., just one of your best episodes - many JS programmers are doing `this` or `that` just because one API set of paradigms or another will give them what they need for their immediate task. But the deep knowledge reside in knowing WHY `this` is better `that` in very a particular or a very general circumstance. It would be perfect if you can talk more about how JS engine is working behind the scene, about JS Event Loop / JS Call Stack / etc. Thanks again for your very explicit shows.
Heeey! Thanks for all that async/await content on Your channel! I did get my first junior react dev job thanks to You! I used async/await and try-catch in my tech meeting interview task, and they were impressed! I'm really, really grateful for that!
This has been a big help James, thanks so much! I have been struggling trying to convert promises to async/await functions and seeing you walk us through it step-by-step really helped a lot!
I personally prefer the .then syntax, instead of multiple try-catch you can catch each promise easily. Async await is a new synthetic sugar that you don't have to use, but may. Plus you can use it on top level as well with no IIFEs or whatever.
Thanks for the wonderful video. All concepts cleared. I was using multiple awaits without understanding the reason behind. The promise.All solution is fantastic. Waiting for more such tutorial.
So, my mindset all this time is wrong. I thought you still have to use then catch with await keyword. Now, i'm fully understand, thank you for this lesson.
Await/async has two very great advantages. If you dont transpile to es5 async functions give better stacktraces. Also error handling is easier to read as many programmers make mistakes about what is the difference between catch and the second optional argument to then
@@BobbyBundlez I'm pretty sure I was just poking fun at his use of "we" when the video is just him, alone. It's a 20-minute video from a year ago though so it's not really worth my time to try and remember. I cannot imagine why it was worth your time commenting to begin with.
The problem with this is that you create a lot of intermediary variables that you're not really gonna use just so you don't have `. then` calls. You could've chained `then`s until you got the data and then awaited on that to get the data on a variable. Async / await isn't meant to eliminate then calls, it's meant to simplify working with them
Good point. I want to mention something else to consider. Having a lot of local variables can be convenient if you're using a debugger because the debugger would show all the values at a glance when it hits a breakpoint in scope. It's not always necessary, of course, but it can be nice sometimes.
Lol no. Async await can and is meant to replace every then. I don't know if you meant it on a performance or readability POV but those intermediary variables you say replace the callbacks, which are also in memory, and variables are much more readable than anon funcs. JS is GC you shouldn't care about that; your concern is wrong but if you are concerned to that level use other lang. I would stare very weirdly to anyone who mixed then calls and await, seriously. If you are going to do that, keep chaining thens and ignore async/await altogether. The mix of both is the WORST posible scenario (in the same function obviously, not at a project level). Not to mention that if you have "a lot" of intermediary variables you are doing something completely wrong.
change your fetch(url1 // etc) to fetch(url1).then(r=>r.json()) and you remove the need for the array map entirely. You can also add .catch to each to handle errors specific to each URL. Just an example of the power of combining await and promises together to make clean code. This trick becomes useful when you end up needing several different resources at the same time (instead of 3 todo's as shown here that return the exact same structure). Invariable some years later one of those calls will change and you will end up using another .then to reformat the data to match whatever it needs to be.
Amazing, just about a few hours I was making several sequential fetch's to an API, and now I crossed with your video, now I feel the power, and how to make then kinda asynchronous again, thanks.
The fact that you and others have to explain how async/await works shows its main disadvantage: it can be confusing and prone to errors, whereas .then() is more human readable and easier to understand. Nevertheless, once you get the hang of it, you end up with very compact and clean code. I really like that. I'd only disagree with the use IIFE for top-level await; you end up with code that is harder to read.
The asynchronous nature in and of itself is extremely confusing regardless of regular promises vs async/await. The need to explain how it works comes from the fact that it's new. Any new feature/syntax that is introduced into a language takes time to adopt and understand.
It’s nice that you made the video, but actually you weren’t wrong then and now the “I was wrong”’ video has misinformation about Promise.all() You do the best with what you have at the time though, I love that you wanted to do the right thing and admit you were wrong …unfortunately you were not. The single threaded nature if JavaScript the language allows it to be predictable but you can call out to host systems and do things in parallel, like for example making request. Simple proof would be just making a quick service that responds after 1 second and you’ll see that the Promise.all() version does in fact take about 1 second while awaiting each takes approx 3. The stuff that does not happen in parallel is placing resolutions in the micro task and dealing with the stack calls as the event loop resolved them but that is trivial compared to the network call. Anyway, nice to try and do the right thing, can’t wait for the I was wrong about being wrong video 🙂
@@adamlbarrett Yep, I'm now scrambling to figure out how to fix this again lol I started overthinking it all while reading comments. I'm creating another video shortly for extra clarification and unlisting the other :)
@@JamesQQuick You may want to dip into parallel vs concurrent when you explain why the Promise.all() happens at the same time. People get pedantic about the word parallel sometimes, and I think that was the cause of the original commenters confusion
Thank you for this video. Really helped me understand not only why but how to migrate from .then to await. As a bonus, you helped me solve the multiple url problem I was going to work on this weekend! Thanks again.
I'm currently working on a project where I needed to upload images to an API and get the returned URL so I could store it in the database, and this video helped in solving the puzzle.
Just a small amendment : results.json() converts json to a js object not vice versa (13:18 ) A quote from MDN web docs: Note that despite the method being named json(), the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object.
If anyone is having trouble using and importing the node-fetch module, changing your files extension from .js to .mjs should do the trick. Alternatively you can also include "type": "module" in your nearest package.json file
I'd like to take a different approach when fetching and parsing to json, you can do await(await fetch(url)).json() and it will return the actual data in just a line of code
Finally works as expected for both approaches. Either with chaining .finally() after .catch()/.then() or in an async/await "finally" block on the try-catch
Watching someone make a coding error on RUclips is the adult version of Steve asking where Blue is. He's right there! We can see his tail! You forgot await!
Great tutorial! You have a great, even keel persona in your presentation and that works great! I have personal OCD sort of things around try catch I am trying to overcome. You made this much more approachable :) Love the use of the .map call to manage the results!!! Great little trick.
This is a great video! but try/catch is not always the best way of catching error for async event... (I know this is just a tutorial probably for entry level fellows, but I really need to point this out for more junior developer who might get misled by this) The reason is, try/catch can potentially make debugging and error handling 10x harder (unless one REALLY knows what exception he/she is trying to catch). For instance, the try/catch will catch both bug in your code or the promises gotten rejected, which is bad!, because it will simply made debugging harder (e.g. if one is using axios npm, he/she will have to face this problem). Another example will be the global try/catch for error handling of api (which is very very common). So instead of just using a bunch of try/catch for async event, one also must know that async function can also be implemented in the following way: const data = await fetch(...) .then(res=>res.json()) .then(json=>json) .catch(err=>err) In this way, you can avoid using a bunch try/catch that can potentially over complicate the code, debugging and error handling processes but still getting the benefits from using async/await.
The reason I'm commenting is because someone else's comment dragged me back here after a year and the reason I disagree with you is this: In JavaScript you should not be using try/catch to catch errors. You should always know exactly how your code can fail and any normal exceptions will show up in your console or IDE. Outside of async operations, Try/Catch is almost never used so who cares if it can catch errors and rejected promises? It should never do the former anyway and if it does, you refactor your code and it never happens again. I found exactly 1 legitimate way to use Try/Catch outside of async functions and I can't even remember what it was now but it had to do with keystrokes and some user input I could reliably get to trigger an exception-I think all it did was save me a few nested "if" statements.
A promise is a wrapped value that you can use for railway oriented programming, your code can be re used if the result is a promise or an async result represented as an object literal like in redux state because the important code is a function that receives a value and error, loading or stale is handled outside of that function. Functions should be doing only one thing so async await forces you to write functions that do more than the one thing and will make re usability and refactoring more difficult. It only looks "cleaner" because you write functions that do too much instead of composing multiple functions that do one thing.
Why? Try-catch should be used often in most/all programming languages. Heck, even SQL has try-catch error handling. It's usually a good idea to have an exception handler for specific scenarios.
@@RyanFlores9 agreed that error handling and try / catch is key. I just like the .catch() method you can use with promises a little better. It’s cleaner. But you’re right try/catch not only works but is needed with async await. It doesn’t stop me from using async await over promises either.
Thanks for sharing ! Will try to apply this to my current react project where i am fetching companies then convert all their adresses to lat, lng with the google geocoding api and then display a google map with all the markers. Would be a nice video ^^
Both Promise sintaxes should be used interchangeably. Looking for readable code and beyond trivial cases, specifically with fine grained error handling, then/catch could also be preferable. I always decide on a case to case basis. There is problem when the async/await syntax is used to mask the fact (or not fully understanding) that you are dealing with promises.
thank you thank you you thank you you thank you you thank you you thank you you thank you you thank you you thank you you thank you you thank you you thank you you thank you i finally understand this
Regards the "top level await" I don't think it's working like that any more (I'm on nodejs v17.0.1) I'm not sure how helpful this could be, but in case someone reads it and has the same error they may now know why :D Still working the "hacky" way and inside async functions (for those who wonder) Anyways, keep up the good work James ;) Error message when using "Top-Level Await" in NodeJs v17.0.1 """ const a = await test(); ^^^^^ SyntaxError: await is only valid in async functions and the top level bodies of modules """
@@JamesQQuick No they are local as they are currently closed source projects But all I did was creating a new folder, made an index.js file, ran npm init -y (to get a plain package.json), this is how the index file looks like, and the package.json hasn't been changed after it was created """ async function test() { return "I'm a Test"; } (async ()=>{ const a = await test(); console.log(a); )() //
Excellent video. You explained things very clearly and coherently. I wish I had your skill to explains things the way you did in this video. This goes without saying that I'm not 100% convinced that I should refactor all my code to use await/async. But I'm glad to see that I have the option and ability to use them. Thanks.
It's worth noting that Promise.all is a weirdly specific implementation of a much deeper/more general concept: a traversal. Any data type that can be made to follow certain laws can do this sort of operation, which is taking any traversable data type and sort of flipping the inner type outwards (so an Array of Promises can be represented as a Promise of an Array). What's weird about the implementation in javascript is that Promise.all is really more what could have been a method on Array, not Promise. It's just that this implementation is built to work specifically with Promises in particular, using their weird naming method convention. If Promises used .map/.flatMap instead of collapsing both into .then it would be more obvious the deeper connection between mapping over an Array vs. mapping over the value in a Promise, making lots of things more interoperable. Alas!
May I suggest that you include links to relevant MDN pages? A lot of people STILL have to deal with IE11 and these types of really nice JS features are just not available, so, if you're new to the games, then this would be a buzz kill. Nice video - keep up the good work!
Just don't use newer JavaScript features if you need to support an audience or customer base that continue to use an outdated/insecure browser. Either force users to switch by displaying a message (after performing a browser detection), or limit those users to an old/nerfed version of your site/app if you do end up wanting to transition to using newer JS features. Your comment reminds of the good 'ol days of needing to continue support for IE5, IE7, IE9... If you're able to get the metrics on the percentage of your users who still use IE11, and the number is (relatively) small, it might be time to just cut your losses on those people. Not to mention, IE11 will reach EOL in June 2022, so is it really worth it to maintain a deprecated/dying code base? Some people just need to learn to move on.
You just don't give a basic example of the usage of asyc/await, you give how to use them in multiple calls scenarios. Great work!!! And thank you for sharing!
I'm glad there a lot of people disagreeing with you. Your video is nice and well explained, but I got to say I prefer ".then" over "async/await". I simply found it way easier to understand. It's closer to how a human would think about something asynchronous. "do this and when you will have the data, then do that." when I was learning JavaScript, the async/await was bugging me and what made me understand it was the "then"
I agree. Seems like a lot of (relatively) newer JavaScript improvements are making it possible to write more lean and compact code, but that doesn't necessarily make it more (human) readable. One could argue it could be due to lack of familiarity, but for me personally, I'd use that argument for learning a new framework/toolkit/API/SDK over an evolving language. I see other languages improving over time, but a lot of changes that were made to JavaScript introduced a lot of inconsistencies IMHO. The changes introduced a lot more "ways to skin a cat" instead of focusing on readability and a single "best/right way" to do things.
I disagree! I can’t wait to get refactoring our messy asynchronous code in my current project! 😂
I have a 300 lines long test and async/await cut execution time from 14 sec to 4. Who cares about human undertanding? Its not for regular bread buyer. You learn it in a day and benefit for life. '.then' is slowwww
.then is just for old people, you need to cope up 😂
Jonathan, you’ll get used to it. It’s cleaner.
I must say I still think working with Promises is a lot more clean than working with async/await. With async/await, you end up with a lot more LOC's, you still have to deal with a promise if values are returned from the async function, or you have to use top-level async/await, which is ultimately undesirable since asynchronous code can lead to frustrating long debugging when not applied correctly in respect to synchronous code.
I agree!
I finally got the idea of async in JS, up to this moment I struggled with understanding sequences of actions when running async code. Now I understand it completely, thanks James!
async/await being syntactically "cleaner" is pretty well a value judgement. There are some real advantages to async/await though, chiefly (1) an asyncFunction is guaranteed to throw by way of returning a rejected promise (or rejecting its returned promise), even from a sync code fail ... the advantage accrues in the caller (2) .then().then() related scope issues disappear ... remember all those "how do I access previous results?" questions in StackOverflow?
I definitely agree on the "cleaner" part, the example from this video is a lot cleaner in the .then syntax IMO. It can also be a lot shorter than the async await version, since it could easily be on 4 lines without losing any clarity. Even though the async await version is a lot more verbose, it's a lot messier than the .then version.
Honestly, the promise.all example was really ugly.
I'd rather just do:
let urls=[....... ]
return Promise.all(
urls.map(
url => fetch(url).then(res=>res.json())
)
)
This is so much cleaner than the example in the vid
@@thatguynamedmorgoth8951 Promise/then hell detected - the then is nested. Should be chained under the Promise.all() call.
@@mlntdrv the then callback would also need to have a map operation which I find kinda ugly, though it's a valid answer
The best video that explains the two different ways of calling async function! await is always much cleaner than the .then .catch.
They both have their place. Promises are cleaner for pipeline type stuff, particularly if you can go point-free:
fetch(url)
.then(res => res.json())
.then(console.log)
.then(console.error)
It's often a more concise syntax, (reduce lines of code by 30%) so can be great for testing also. Also less cognitive load.
Async await has its place, especially for writing big chunks of procedural code where you really need space to work in. Also it's easier to debug.
Very much that, babs.
One other thing to probably be weary of, if you have too many await statements or long chained promises and then succeed them by some logic that is not directly related to the response they generate, you would potentially block JS from rendering the UI. Its important to put all your awaits only within an async function scope and not do anything else in there.
I think that a good example of that is using observables in typescript
I finally learned how to use the Promise.all method in an Async/Await function. Thanks, bro for your work...
You’re very welcome!!
One of the clearest explanation of async/await I have ever seen. Thanks James!!
Yeahhhh!!
I can finaly say I understand all this promises and async stuff. This video was perfect to wrap it all.
..., just one of your best episodes - many JS programmers are doing `this` or `that` just because one API set of paradigms or another will give them what they need for their immediate task. But the deep knowledge reside in knowing WHY `this` is better `that` in very a particular or a very general circumstance. It would be perfect if you can talk more about how JS engine is working behind the scene, about JS Event Loop / JS Call Stack / etc. Thanks again for your very explicit shows.
Heeey! Thanks for all that async/await content on Your channel! I did get my first junior react dev job thanks to You! I used async/await and try-catch in my tech meeting interview task, and they were impressed! I'm really, really grateful for that!
This has been a big help James, thanks so much! I have been struggling trying to convert promises to async/await functions and seeing you walk us through it step-by-step really helped a lot!
Thanks! I'm new to JS and building the back end of a web app. This is exactly the info I was looking for.
I personally prefer the .then syntax, instead of multiple try-catch you can catch each promise easily. Async await is a new synthetic sugar that you don't have to use, but may.
Plus you can use it on top level as well with no IIFEs or whatever.
I think you mean syntactic sugar?
Thanks for the wonderful video. All concepts cleared. I was using multiple awaits without understanding the reason behind. The promise.All solution is fantastic. Waiting for more such tutorial.
So glad this was helpful!! :)
So, my mindset all this time is wrong. I thought you still have to use then catch with await keyword. Now, i'm fully understand, thank you for this lesson.
Thank you!!! i was stuck with this for 2 days but now I was able to solve the problem.
Amazing tutorial.
Await/async has two very great advantages. If you dont transpile to es5 async functions give better stacktraces. Also error handling is easier to read as many programmers make mistakes about what is the difference between catch and the second optional argument to then
" *We* completely missed that"-Hey man you're flying solo on this one.
What? lol
The haters on these comments is just so funny. Shut up bro this tutorial is great
@@BobbyBundlez I'm pretty sure I was just poking fun at his use of "we" when the video is just him, alone. It's a 20-minute video from a year ago though so it's not really worth my time to try and remember. I cannot imagine why it was worth your time commenting to begin with.
@@stevenleonmusic says the person who replied with an entire essay
@@zeta519 Buddy if you think that's an essay all I can say is you need to read more.
The problem with this is that you create a lot of intermediary variables that you're not really gonna use just so you don't have `. then` calls. You could've chained `then`s until you got the data and then awaited on that to get the data on a variable.
Async / await isn't meant to eliminate then calls, it's meant to simplify working with them
Good point. I want to mention something else to consider. Having a lot of local variables can be convenient if you're using a debugger because the debugger would show all the values at a glance when it hits a breakpoint in scope. It's not always necessary, of course, but it can be nice sometimes.
Can't you just do this?
const data = await (await fetch(url)).json();
@@akashchoudhary8162 you can, but IMHO it's the hardest one to read
exactly, there is no real need to purposefully refactoring existing code to async/await.
Lol no. Async await can and is meant to replace every then. I don't know if you meant it on a performance or readability POV but those intermediary variables you say replace the callbacks, which are also in memory, and variables are much more readable than anon funcs. JS is GC you shouldn't care about that; your concern is wrong but if you are concerned to that level use other lang.
I would stare very weirdly to anyone who mixed then calls and await, seriously. If you are going to do that, keep chaining thens and ignore async/await altogether. The mix of both is the WORST posible scenario (in the same function obviously, not at a project level). Not to mention that if you have "a lot" of intermediary variables you are doing something completely wrong.
change your fetch(url1 // etc) to fetch(url1).then(r=>r.json()) and you remove the need for the array map entirely. You can also add .catch to each to handle errors specific to each URL. Just an example of the power of combining await and promises together to make clean code. This trick becomes useful when you end up needing several different resources at the same time (instead of 3 todo's as shown here that return the exact same structure). Invariable some years later one of those calls will change and you will end up using another .then to reformat the data to match whatever it needs to be.
Amazing, just about a few hours I was making several sequential fetch's to an API, and now I crossed with your video, now I feel the power, and how to make then kinda asynchronous again, thanks.
this is one of the most useful videos I have watched in a long time. Thanks man 👍
The fact that you and others have to explain how async/await works shows its main disadvantage: it can be confusing and prone to errors, whereas .then() is more human readable and easier to understand. Nevertheless, once you get the hang of it, you end up with very compact and clean code. I really like that. I'd only disagree with the use IIFE for top-level await; you end up with code that is harder to read.
The asynchronous nature in and of itself is extremely confusing regardless of regular promises vs async/await. The need to explain how it works comes from the fact that it's new. Any new feature/syntax that is introduced into a language takes time to adopt and understand.
Wow -- a tough topic and you managed to explain it with good examples.
Hey all! I have a few clarifications about Promise.all coming in a new video shortly.
It’s nice that you made the video, but actually you weren’t wrong then and now the “I was wrong”’ video has misinformation about Promise.all()
You do the best with what you have at the time though, I love that you wanted to do the right thing and admit you were wrong …unfortunately you were not.
The single threaded nature if JavaScript the language allows it to be predictable but you can call out to host systems and do things in parallel, like for example making request.
Simple proof would be just making a quick service that responds after 1 second and you’ll see that the Promise.all() version does in fact take about 1 second while awaiting each takes approx 3.
The stuff that does not happen in parallel is placing resolutions in the micro task and dealing with the stack calls as the event loop resolved them but that is trivial compared to the network call.
Anyway, nice to try and do the right thing, can’t wait for the I was wrong about being wrong video 🙂
@@adamlbarrett Yep, I'm now scrambling to figure out how to fix this again lol I started overthinking it all while reading comments. I'm creating another video shortly for extra clarification and unlisting the other :)
@@JamesQQuick I immediately regretted adding to the cesspool that is "RUclips comments" as soon as I posted it. But good luck with this whole thing!
@@JamesQQuick You may want to dip into parallel vs concurrent when you explain why the Promise.all() happens at the same time.
People get pedantic about the word parallel sometimes, and I think that was the cause of the original commenters confusion
@@adamlbarrett Uploading a new video shortly and mention a bit of the difference there!
Thank you for this video. Really helped me understand not only why but how to migrate from .then to await. As a bonus, you helped me solve the multiple url problem I was going to work on this weekend! Thanks again.
Glad it was helpful!
super awesome tutorial!!!
i learned async/await in first 5 minutes of video.best video.❤❤❤❤❤❤❤❤
much love from iran
Thank you!
James, you are a legend :) have seen multiple of your videos and your approach to coding is very inspiring.
Clearest explanation I've found for how these all relate. Thanks!
Really well explained. Thank you.
I'm currently working on a project where I needed to upload images to an API and get the returned URL so I could store it in the database, and this video helped in solving the puzzle.
yasss!!
Very clear explanation! Thank you so much!
I think this cannel is the most useful one about programming, especially for JS. Thank you!
Yassss! :)
Thx, helped me a lot to improve some ugly parts in a current project. Specially the part with Promise.all.
const content = James Q Quick
const res= await fetch(content)
console.log("GREAT STUFF!")
thank you for explaining properly how getting that data needs to be handled by a .then. I tried understanding stack overflow but they just rude lol
Just a small amendment : results.json() converts json to a js object not vice versa (13:18 )
A quote from MDN web docs:
Note that despite the method being named json(), the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object.
Wow!! I was literally waiting for this content...very nicely explained❤️ thanks James..
Great explanation. Cristal clear
If anyone is having trouble using and importing the node-fetch module, changing your files extension from .js to .mjs should do the trick. Alternatively you can also include
"type": "module"
in your nearest package.json file
Congratulations
Finally. A good path to understand. Tks man.
Perfect explanation!
Thank you, James.
I'd like to take a different approach when fetching and parsing to json, you can do await(await fetch(url)).json() and it will return the actual data in just a line of code
Thanks this helped , especially the Promise.all() part.
Really great content. When you start having multiples functions across multiple files handling promises gets hard as hell.
very helpful video, easy to understand
fetch(url).then(res=>res.json()).then(console.log).catch(console.error);
Anyway: what about `finally`?
Finally works as expected for both approaches. Either with chaining .finally() after .catch()/.then() or in an async/await "finally" block on the try-catch
Watching someone make a coding error on RUclips is the adult version of Steve asking where Blue is. He's right there! We can see his tail! You forgot await!
Great tutorial!
You have a great, even keel persona in your presentation and that works great!
I have personal OCD sort of things around try catch I am trying to overcome. You made this much more approachable :)
Love the use of the .map call to manage the results!!! Great little trick.
Thnak you. Excellent video.
Loved this one! Thanks for clearing it out for me. Keep it up!! 🚀🎉
This is a great video! but try/catch is not always the best way of catching error for async event... (I know this is just a tutorial probably for entry level fellows, but I really need to point this out for more junior developer who might get misled by this)
The reason is, try/catch can potentially make debugging and error handling 10x harder (unless one REALLY knows what exception he/she is trying to catch).
For instance, the try/catch will catch both bug in your code or the promises gotten rejected, which is bad!, because it will simply made debugging harder (e.g. if one is using axios npm, he/she will have to face this problem). Another example will be the global try/catch for error handling of api (which is very very common).
So instead of just using a bunch of try/catch for async event, one also must know that async function can also be implemented in the following way:
const data = await fetch(...)
.then(res=>res.json())
.then(json=>json)
.catch(err=>err)
In this way, you can avoid using a bunch try/catch that can potentially over complicate the code, debugging and error handling processes but still getting the benefits from using async/await.
The reason I'm commenting is because someone else's comment dragged me back here after a year and the reason I disagree with you is this: In JavaScript you should not be using try/catch to catch errors. You should always know exactly how your code can fail and any normal exceptions will show up in your console or IDE. Outside of async operations, Try/Catch is almost never used so who cares if it can catch errors and rejected promises? It should never do the former anyway and if it does, you refactor your code and it never happens again. I found exactly 1 legitimate way to use Try/Catch outside of async functions and I can't even remember what it was now but it had to do with keystrokes and some user input I could reliably get to trigger an exception-I think all it did was save me a few nested "if" statements.
This helped a lot. Thanks ma!
A promise is a wrapped value that you can use for railway oriented programming, your code can be re used if the result is a promise or an async result represented as an object literal like in redux state because the important code is a function that receives a value and error, loading or stale is handled outside of that function.
Functions should be doing only one thing so async await forces you to write functions that do more than the one thing and will make re usability and refactoring more difficult. It only looks "cleaner" because you write functions that do too much instead of composing multiple functions that do one thing.
Nice explanation! I am always bummed though to use try / catch for error handling. I wish async / await had some better way to handle that. Thanks!
Why? Try-catch should be used often in most/all programming languages. Heck, even SQL has try-catch error handling. It's usually a good idea to have an exception handler for specific scenarios.
@@RyanFlores9 agreed that error handling and try / catch is key. I just like the .catch() method you can use with promises a little better. It’s cleaner. But you’re right try/catch not only works but is needed with async await. It doesn’t stop me from using async await over promises either.
Very neat.
Dumb question: what is this tool that you are using for editing and viewing results?
Thanks!
Man it's going to make my life easier, thank you.
Yayyyyyy
Thank you for this awesome explanation and demonstration!
Thank you!!!! Very understandable!
Thanks for sharing ! Will try to apply this to my current react project where i am fetching companies then convert all their adresses to lat, lng with the google geocoding api and then display a google map with all the markers. Would be a nice video ^^
Great material, thank you very much!!!!!!!!!!!!!!!!!!!!!!
Useful advice 👍
Thank you soooo much!!! this really helped.
Thanks, James
Then, Catch imo is visually readable, it visually displays the sequence of actions, and forces you to plan on what data to pass to the next action.
great tuto ! thank you!
Both Promise sintaxes should be used interchangeably. Looking for readable code and beyond trivial cases, specifically with fine grained error handling, then/catch could also be preferable. I always decide on a case to case basis.
There is problem when the async/await syntax is used to mask the fact (or not fully understanding) that you are dealing with promises.
I haven't really found a use case for me to use .then instead of async/await, so I use it all the time.
amazing tutorial thanks.
nicely explained.. just gone fear about async, await.. thanks a lot.
Both valid, all preference
thank you thank you you thank you you thank you you thank you you thank you you thank you you thank you you thank you you thank you you thank you you thank you you thank you i finally understand this
Cool tips James. What is the benefit using Asycn await?
Thank you for sharing this with us very helpful.
Regards the "top level await"
I don't think it's working like that any more (I'm on nodejs v17.0.1)
I'm not sure how helpful this could be, but in case someone reads it and has the same error
they may now know why :D
Still working the "hacky" way and inside async functions (for those who wonder)
Anyways, keep up the good work James ;)
Error message when using "Top-Level Await" in NodeJs v17.0.1
"""
const a = await test();
^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules
"""
It may be that you have to change to modules in your package.json. DId you change anything there?
@@JamesQQuick Nope didn't change anything. Tested on both an existing project and a completely new project.
@@MaxioGamingExp hmm do you have a sample repo?
@@JamesQQuick No they are local as they are currently closed source projects
But all I did was creating a new folder, made an index.js file, ran npm init -y (to get a plain package.json),
this is how the index file looks like, and the package.json hasn't been changed after it was created
"""
async function test() {
return "I'm a Test";
}
(async ()=>{
const a = await test();
console.log(a);
)() //
I wanna marry your code it looks so clean :)
even though I've been using this stuff for a good while now, the Promise.all part was really useful :D
Thank you
Well sumed up mate
Super helpful video. Thank you!
Glad it was helpful!
Awesome explanation!
PS: high-level await doesn't work on Node v19.4.0
Excellent video. You explained things very clearly and coherently. I wish I had your skill to explains things the way you did in this video. This goes without saying that I'm not 100% convinced that I should refactor all my code to use await/async. But I'm glad to see that I have the option and ability to use them. Thanks.
Glad this was helpful. It's definitely good to be aware of your options1
Muito bom, parabéns. Sempre achei um problema utilizar Async/Await
Thanks dude!
Really great video! Many good insights on how promises work. I agree async/await > .then
Maybe in some scenarios, but not all.
I think a lot of people propagate this idea that Async/Await is better than ".then". It's not really cleaner it's just different.
Error handling is especially different between the two approaches. I agree with you.
thank you man.
The amount of hate in these comments and pestering nerds trying to one up is so funny. Relax guys. Thanks for the tutorial
Nice work♥️
Both are valid!
lovely !!
It's worth noting that Promise.all is a weirdly specific implementation of a much deeper/more general concept: a traversal. Any data type that can be made to follow certain laws can do this sort of operation, which is taking any traversable data type and sort of flipping the inner type outwards (so an Array of Promises can be represented as a Promise of an Array). What's weird about the implementation in javascript is that Promise.all is really more what could have been a method on Array, not Promise. It's just that this implementation is built to work specifically with Promises in particular, using their weird naming method convention. If Promises used .map/.flatMap instead of collapsing both into .then it would be more obvious the deeper connection between mapping over an Array vs. mapping over the value in a Promise, making lots of things more interoperable. Alas!
Thanks a lot for sharing this! This really helped.
Really useful, promise.all was always a pain to me, now I understand how to use it. Thank you!!
Great as always, thank you.
Great explanation!
May I suggest that you include links to relevant MDN pages? A lot of people STILL have to deal with IE11 and these types of really nice JS features are just not available, so, if you're new to the games, then this would be a buzz kill.
Nice video - keep up the good work!
Just don't use newer JavaScript features if you need to support an audience or customer base that continue to use an outdated/insecure browser. Either force users to switch by displaying a message (after performing a browser detection), or limit those users to an old/nerfed version of your site/app if you do end up wanting to transition to using newer JS features. Your comment reminds of the good 'ol days of needing to continue support for IE5, IE7, IE9... If you're able to get the metrics on the percentage of your users who still use IE11, and the number is (relatively) small, it might be time to just cut your losses on those people. Not to mention, IE11 will reach EOL in June 2022, so is it really worth it to maintain a deprecated/dying code base? Some people just need to learn to move on.