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 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!
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.
@@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.
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!
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
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'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
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!
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.
..., 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.
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.
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.
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
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
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.
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.
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
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 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'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
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.
Watching someone make a coding error on UA-cam is the adult version of Steve asking where Blue is. He's right there! We can see his tail! You forgot await!
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.
Since I started writing a JS SDK a while ago, I’m using Promises with then/catch a lot and without running into issues like “unhandledrejection” which you should catch, regardless. Especially when using promises in class constructors where Async/Await is not an option.
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
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.
I may be overcomplicating a simple example here, and really appreciate the video, but I'm trying to move to JS (actually tyoescript) from hard-real-time embedded C. I'm wondering why you would bother with the final "await". The last line of your function is effectively "return (await promise.all(...));". So, you wait here for all the promises to resolve and then return the data. But an async function always returns a promise, which means it has to be called as either "await foo" or "foo.then()". In which case, why not simply "return promise.all(...)" and let the caller decide when they want to do the final synchronous wait? Is this a best practice idiom or is there something fundamental I'm missing?
I think I'm seeing an overcomplication from a simple example as well. Finding async/await can create lots of spaghetti in the wrong hands. It returns promises either way so there's no escaping then(). Then catch() is merely replaced with a try{}catch{} here. 6 and 1/2 dozen of the other? And arguments support await so inside your LoadData() I can just invoke a topLevelFunction(await res.json()); which topLevelFunction has no async/await awareness on. There's a million ways to skin a cat these days and it can be far too much nuance, which you did preface this with.
Maybe because as the error states, you're using await in a function not declared as async, or you're not using await in a function at all. An example would be useful.
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 ^^
Worth noting you didn't need to `await res.json()` or pass the mapped array to `Promise.all`. This only works because `await`ing a non-Promise value simply creates a new Promise and resolves immediately to the value `await`ed. You shouldn't do that, though.
Please note that response.json() returns a promise and therefore the await is necessary. The response object is available as soon as the headers have arrived - however the response body may not have yet arrived and been processed which is why response.json() has to be asynchronous.
Hi, can you please help with my question that follows below 2 approaches of the same logic? Approach 1: const apiURls = ['url1','url2','url3']; (async ()=> { const result = await Promise.all(apiURLs.map(async(url)=> { await fetch(url) })); return result; })(); Approach 2: const url1 = "url1", url2= "url2", url3=" url3"; (async()=> { const result = await Promis.all([ await fetch(url1), //step 1 await fetch(url2), //step 2 await fetch(url3) //step 3 ]); return result; })(); In the above two approaches, I see no difference in terms of their functionalities. However, why does only the 2nd approach seem to run in the sequence it is being called? (i.e url1 followed by url2 and url3) But, the 1st approach calls the fetch call randomly, and not in the sequence of the apiURLs array.
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.
I prefer using then, fail, catch, done... rather using await keyword for fetching data from a backend side, for me to validate response without using a conditional statement such as check the response if 200 etc.. and also to separate the process where what the program do if a request successfully make a responds or the request thrown an error or what to do if the request is successfully send to the server wether it is error or has a responds then ( ... successfully has a responds ) fail ( ... has an error ... ) done (... make a request ...) it is more cleaner, readable and easy to maintain
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
await keyword applied to a promise gets us the value asynchronously WITHOUT blocking const name = await getNamePromise(); console.log(name); //name here will have the result available and not the promise object because we used await Await needs to be used inside an async function
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.
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 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!
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!
" *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.
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!
The best video that explains the two different ways of calling async function! await is always much cleaner than the .then .catch.
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
I finally learned how to use the Promise.all method in an Async/Await function. Thanks, bro for your work...
You’re very welcome!!
I can finaly say I understand all this promises and async stuff. This video was perfect to wrap it all.
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'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.
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!
One of the clearest explanation of async/await I have ever seen. Thanks James!!
Yeahhhh!!
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.
..., 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.
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.
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.
7:10 wait, how do i get the data in a variable if what i want is to use that and not print the results in console
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 "UA-cam 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!
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!! :)
Thank you!!! i was stuck with this for 2 days but now I was able to solve the problem.
Amazing tutorial.
this is one of the most useful videos I have watched in a long time. Thanks man 👍
Thanks! I'm new to JS and building the back end of a web app. This is exactly the info I was looking for.
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.
Wow -- a tough topic and you managed to explain it with good examples.
James, you are a legend :) have seen multiple of your videos and your approach to coding is very inspiring.
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
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.
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!
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
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.
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?
Clearest explanation I've found for how these all relate. Thanks!
Wow!! I was literally waiting for this content...very nicely explained❤️ thanks 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
Really well explained. Thank you.
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.
Very neat.
Dumb question: what is this tool that you are using for editing and viewing results?
Thanks!
Perfect explanation!
Thank you, James.
Great explanation. Cristal clear
Thanks this helped , especially the Promise.all() part.
Man it's going to make my life easier, thank you.
Yayyyyyy
I wanna marry your code it looks so clean :)
very helpful video, easy to understand
Congratulations
Finally. A good path to understand. Tks man.
This helped a lot. Thanks ma!
Thx, helped me a lot to improve some ugly parts in a current project. Specially the part with Promise.all.
The amount of hate in these comments and pestering nerds trying to one up is so funny. Relax guys. Thanks for the tutorial
Thnak you. Excellent video.
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
Very clear explanation! Thank you so much!
Thank you soooo much!!! this really helped.
super awesome tutorial!!!
i learned async/await in first 5 minutes of video.best video.❤❤❤❤❤❤❤❤
much love from iran
Thank you!
Thank you!!!! Very understandable!
Watching someone make a coding error on UA-cam is the adult version of Steve asking where Blue is. He's right there! We can see his tail! You forgot await!
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 material, thank you very much!!!!!!!!!!!!!!!!!!!!!!
In the example of .then in the beginning, there's an error. Instead of "console.error(error) is should have been "console.error(err)"
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.
Since I started writing a JS SDK a while ago, I’m using Promises with then/catch a lot and without running into issues like “unhandledrejection” which you should catch, regardless.
Especially when using promises in class constructors where Async/Await is not an option.
I think this cannel is the most useful one about programming, especially for JS. Thank you!
Yassss! :)
amazing tutorial thanks.
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
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.
even though I've been using this stuff for a good while now, the Promise.all part was really useful :D
great tuto ! thank you!
I may be overcomplicating a simple example here, and really appreciate the video, but I'm trying to move to JS (actually tyoescript) from hard-real-time embedded C. I'm wondering why you would bother with the final "await".
The last line of your function is effectively "return (await promise.all(...));". So, you wait here for all the promises to resolve and then return the data. But an async function always returns a promise, which means it has to be called as either "await foo" or "foo.then()".
In which case, why not simply "return promise.all(...)" and let the caller decide when they want to do the final synchronous wait? Is this a best practice idiom or is there something fundamental I'm missing?
You’re spot on you could definitely do that! Just an oversight on my end
I think I'm seeing an overcomplication from a simple example as well. Finding async/await can create lots of spaghetti in the wrong hands. It returns promises either way so there's no escaping then(). Then catch() is merely replaced with a try{}catch{} here. 6 and 1/2 dozen of the other? And arguments support await so inside your LoadData() I can just invoke a topLevelFunction(await res.json()); which topLevelFunction has no async/await awareness on. There's a million ways to skin a cat these days and it can be far too much nuance, which you did preface this with.
nicely explained.. just gone fear about async, await.. thanks a lot.
Thanks, James
Thank you for this awesome explanation and demonstration!
Useful advice 👍
Super helpful video. Thank you!
Glad it was helpful!
at 9:03, I cannot do like this, I got "await is only valid in async functions and the top level bodies of modules" with node 16
Maybe because as the error states, you're using await in a function not declared as async, or you're not using await in a function at all. An example would be useful.
Cool tips James. What is the benefit using Asycn await?
Really great video! Many good insights on how promises work. I agree async/await > .then
Maybe in some scenarios, but not all.
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 ^^
Thank you for sharing this with us very helpful.
Both valid, all preference
Worth noting you didn't need to `await res.json()` or pass the mapped array to `Promise.all`. This only works because `await`ing a non-Promise value simply creates a new Promise and resolves immediately to the value `await`ed. You shouldn't do that, though.
Ah shoot did I make that mistake? Great catch!
I'm glad I wasn't the only who caught that. No wonder why I got confused and thrown off at that part of the video.
Please note that response.json() returns a promise and therefore the await is necessary. The response object is available as soon as the headers have arrived - however the response body may not have yet arrived and been processed which is why response.json() has to be asynchronous.
Hi, can you please help with my question that follows below 2 approaches of the same logic?
Approach 1:
const apiURls = ['url1','url2','url3'];
(async ()=> {
const result = await Promise.all(apiURLs.map(async(url)=> {
await fetch(url)
}));
return result;
})();
Approach 2:
const url1 = "url1", url2= "url2", url3=" url3";
(async()=> {
const result = await Promis.all([
await fetch(url1), //step 1
await fetch(url2), //step 2
await fetch(url3) //step 3
]);
return result;
})();
In the above two approaches, I see no difference in terms of their functionalities. However, why does only the 2nd approach seem to run in the sequence it is being called? (i.e url1 followed by url2 and url3) But, the 1st approach calls the fetch call randomly, and not in the sequence of the apiURLs array.
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.
Well sumed up mate
Is it possible to chain the methods with async await, as in "const data = await fetch(url).json();" ???
Great explanation!
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.
Awesome! Thanks, learnt heaps.
Great as always, thank you.
Thanks dude!
Thanks a lot for sharing this! This really helped.
Nice work♥️
Muito bom, parabéns. Sempre achei um problema utilizar Async/Await
Really great content. When you start having multiples functions across multiple files handling promises gets hard as hell.
I prefer using then, fail, catch, done... rather using await keyword for fetching data from a backend side, for me to validate response without using a conditional statement such as check the response if 200 etc.. and also to separate the process where what the program do if a request successfully make a responds or the request thrown an error or what to do if the request is successfully send to the server wether it is error or has a responds
then ( ... successfully has a responds )
fail ( ... has an error ... )
done (... make a request ...)
it is more cleaner, readable and easy to maintain
Awesome explanation!
PS: high-level await doesn't work on Node v19.4.0
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
await keyword applied to a promise gets us the value asynchronously WITHOUT blocking
const name = await getNamePromise();
console.log(name); //name here will have the result available and not the promise object because we used await
Await needs to be used inside an async function
At 13:22 could we ude reduce instead of map?
will it also work?
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.
const content = James Q Quick
const res= await fetch(content)
console.log("GREAT STUFF!")