Тёмный

Is async / await useless? 

Fun Fun Function
Подписаться 263 тыс.
Просмотров 58 тыс.
50% 1

💖 This episode is sponsored by Tiptapp, they are currently hiring. If you know someone that would like to work with React Native or node.js in the heart of Stockholm, send them to tiptapp.com/fff
🔗 Support the show by becoming a Patreon
• Patreon + Fun Fun Foru...
🔗 Fun Fun Forum topic for the video
www.funfunforu...
🔗 Async / Await video
• async / await in JavaS...
🔗 Pair programming a messenger bot video
• Pair Programming a Fac...
🔗 mpj on Twitter
/ mpjme
🔗 Help translate the show to your language
www.youtube.com...
I don’t actually believe that, but I would like to do a thought experiment where we test the hypothesis that all async / await code in JavaScript can be re-written just as well using promises, and that async / await doesn’t really add much value to JavaScript.
💛 Follow on Twitch and support by becoming a Subscriber
We record the show live Mondays 7 AM PT
/ funfunfunction
💛 Fun Fun Forum
Private discussion forum with other viewers in between shows. www.funfunforu.... Available to patron members, become one at / funfunfunction
💛 mpj on Twitter
/ mpjme
💛 CircleCI (Show sponsor)
Robust and sleek Docker-based Continuous Integration as a service. I used CircleCI prior to them becoming a sponsor and I love that their free tier is powerful enough for small personal projects, even if they are private. Use this link when you sign up to let them know you came from here:
circleci.funfu...
💛 Quokka (Show sponsor)
Wonder how MPJ evaluates JavaScript inline his editor. Quokka is the answer - use this link when you buy to let them know you came from here:
quokka.funfunfu...
💛 FUN FUN FUNCTION
Since 2015, Fun Fun Function (FFF) is one of the longest running weekly RU-vid shows on programming 🏅 thanks to its consistency and quality reaching 200,000+ developers.
🤦‍♂️ The Failing Together concept is what makes FFF unique. Most coding content out there focus on step-by-step tutorials. We think tutorials are too far removed from what everyday development is like. Instead, FFF has created a completely new learning environment where we grow from failure, by solving problems while intensively interacting with a live audience.
Tutorials try to solve a problem. Failing Together makes you grow as a developer and coworker.
📹 Each show is recorded live on Twitch in a 2-hour livestream on Mondays. The host, assisted by the audience, is tasked to complete a programming challenge by an expert guest. Like in the real world, we often fail, and learn from it. This, of course, reflects what the audience identifies with, and is one of the most praised aspects of the show.
⏯ On Fridays, an edited version of the show is adapted for and published on RU-vid.
Content Topics revolve around: JavaScript, Functional Programming, Software Architecture, Quality Processes, Developer Career and Health, Team Collaboration, Software Development, Project Management

Опубликовано:

 

30 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 358   
@funfunfunction
@funfunfunction 6 лет назад
💖 This episode is sponsored by Tiptapp, they are currently hiring. Work with React Native or node.js in the heart of Stockholm. tiptapp.com/fff
@andrerothweiler9191
@andrerothweiler9191 5 лет назад
Work in a country with a tax rate up to 60% and over 50 no go areas? No, thank you!
@cryptochannels7433
@cryptochannels7433 6 лет назад
Conciseness, readability & maintainability > Cleverness.
@DavidWMiller
@DavidWMiller 6 лет назад
Certainly, what was referred to as "clever" in this video I have very different words for ;)
@Seedzification
@Seedzification 6 лет назад
yes his one liner mess, I wouldn't call that clever at all
@zeeeeeman
@zeeeeeman 6 лет назад
Agreed. A one liner in ternaries is impenetrable to console.log. Good for code golf, not for real world.
@JohnWick-rc9qq
@JohnWick-rc9qq 6 лет назад
Functional programming relies heavily on ternaries and recursion as it favors expressions over statements. They're very useful for the real world. It just takes a little getting used to if you've used `if` and `for` your entire life. It' just like learning any language feature -- you're not comfy until you know it.
@electroaddiction
@electroaddiction 5 лет назад
@@JohnWick-rc9qqIf every developer takes a little to get used to, I wonder the amount of time wasted in the end.
@hamaralsilva
@hamaralsilva 6 лет назад
This video can be renamed to "how to get things worse by using promises instead of async/await". 😂
@rudde7251
@rudde7251 6 лет назад
This is proof JavaScript developers have the highest occurrence of hipsters.
@Assassunn
@Assassunn 6 лет назад
But async DOES return a promise, and await waits a promise is resolved while stopping the execution of the following instructions (which wouldn't be possible using then() ! and that's the power of async/await, not a sugar syntax feature)
@gillianbc
@gillianbc 4 года назад
I can see the advantage of this when you put the generic waitForEach() into a utility module. In your code module, you only then need to define the function you want applying to each of the items. It does make it cleaner and more readable
@AngusMcIntyre
@AngusMcIntyre 6 лет назад
Replacing loops with recursion is exactly the sort of behaviour that async/await is trying to avoid - the transpiler emits this code so that you don't have to. Recursion is harder to reason about and you can introduce all sorts of fun performance issues. For example - how many arrays have you created there? Long story short - you rewrote the async/await code with more characters, more calls and more conditions. Would you write for-loops with goto? 😉
@AjdenTowfeek
@AjdenTowfeek 6 лет назад
First of all, big fan of your show, but you guys really struggled trying to argue that async await is useless in this episode and imho failed miserably ;-) From my experience simplicity and readability is always preferable over complexity especially in larger organizations where the skill may vary quite a lot among the developers. Developers being proud of being clever when performing such basic operations/tasks is usually a red flag. Nobody in their right mind can say that the second (sql) sample is more readable and more straightforward after the refactoring. You guys literally made me laugh when you couldn’t motivate why the refactored code was better other than “I like it because it’s recursion, it’s neat because it’s recursion, it just feels *arghh*”, really? The code became more complex after the refactoring and the argument that it makes you think harder to write that code comes up short imo. You said it yourself, “it’s hard for me to figure it out, but once I have it, it’s simple”. Honestly which code would you prefer to debug and find bugs in? Something you understands immediately and could write up without even thinking or something that feels so great because it’s recursion but you don’t understand it right away?
@funfunfunction
@funfunfunction 6 лет назад
We did not argue that. :)
@danilocecilia7831
@danilocecilia7831 6 лет назад
for me being a 'noob' , as my point of view, the first example is way better understandable and honestly I am still trying to figure it out the recursive refractory solution, feel so stupid right now... =(
@iandashb
@iandashb 6 лет назад
Async/await removes a lot of cognitive load from the Devs trying to work out what the recursive function is doing in the Promise rewrite. The asynchronous/await would be my preference, especially for debugging, but interesting point about error handling....
@JoshuaMuniandy
@JoshuaMuniandy 6 лет назад
I agree. As a noob programmer, I always find Promises daunting. But when I started learning Async Await, I found it easier to code, read & debug. I found that 2nd example of the SQL code was way too complexed esp with the recursion.
@adambechtold6741
@adambechtold6741 6 лет назад
They also missed an obvious opportunity to run their processUser function in parallel. Instead of calling await in the for loop, they could have collected those promises in an array with awaited Promise.all(). In many cases, this would have been faster than both their examples.
@BrandonBey
@BrandonBey 6 лет назад
Oh no, is MPJ saying you should write clever code again :( Code styles are mostly a personal preference thing - if you are writing for yourself, go ahead and be clever. If you are wiring code that is to be shared - making it less clever and more clear is always better.
@LucasVieira42
@LucasVieira42 6 лет назад
Don't be clever, write stupid code. You can write stupid code using Promises, I think you missed the opportunity to show it on this video. Stop this ternary madness (:
@victorb9503
@victorb9503 6 лет назад
Where I'm working on right now (and in most previous gigs actually) we are used among other things to write API tests which by nature are async: do this to the db, make a http request, check how the db changed after that request was completed successfully, etc. And we used to do that with either Promises or the "async" js library. When async await got into the lts version of node.js I took one of the test files and converted it, then looked at the diff. Not only was far fewer lines (I think it was a 2x reduction in total lines) but the identitation was kept to a minimum and the lines were easier to follow and read out loud.
@emretekince
@emretekince 6 лет назад
of course it's useful. simple, clear and readable code!
@AndreasWindt
@AndreasWindt 6 лет назад
Exactly! As satisfying as it can be to come up with a solution like the one in the second example, it might become very hard to grasp what it does at first sight (one could say, »it was hard to write, it has to be hard to read«). I'd definitely prefer the async/await form of it for maintainability!
@nachovalera5217
@nachovalera5217 6 лет назад
I like your video because it shows to me async/await is life❤️ even if you don't want to prove that I understand what happens behind async / await and I think it is a great improvement to the lenguage because it helps you solve real tasks faster and helps you think at a higher level I like that type of promises hell for educational purposes but not that much for real life anymore having async/await
@TheMasterpikaReturn
@TheMasterpikaReturn 6 лет назад
Some thoughts as I watch the video. Also, I'm a functional programming enthusiast, and use quite a lot of haskell in my free time, so there will be a lot of Haskell comparisons. 1- Is async await useless? I'm torn on this one. These days I mainly write Haskell in my free time, and async-await feels like an ad-hoc version of do-notation (much like promises feel like an ad-hoc version of a generic monad typeclass). So I wouldn't say it's useless, but the fact that they had to add an ad-hoc syntax for an ad-hoc construct kinda bothers me. 2- I think code with promises would be much clearer if "if" was an expression instead of a statement... 3- Couldn't you get rid of the nesting by just wrapping `server.getMaxNumberOfBurgersPerDay()` in a Promise[.resolve()], so you can call `then` after the outer `then`? (so it becomes server.hasBurgers().then(.....).then(....)). 4- I don't agree with the "in your face" thing: personally I think that asynchronous flow should be as implicit as possible. For example, haskell's I/O is non-blocking, but while coding you don't really think about it. In my opinion, we should be able to program in a style that looks like synchronous code, but can be asynchronous, and it should be the language's job to transform between those representations. It's a lot like callback hell: it's pretty much Continuation Passing Style, and you can do it manually... but why do it when you can have a CPS-like Monad (like haskell's Cont") and write code that doesn't really look like CPS (albeit with the occasional callCC)? 5 - in the for loop example, i'd think you could so something like `users.map(user => await processUser(user.id))`, can't you? 6 - wait for each looks like a fold dying to come out. Maybe some sort of `compose(foldr(then), map(processFn)`? [where then(a,b) = a.then(b) 7- also, array destructuring feels like ad-hoc pattern matching :D although I guess it's not as ad-hoc, cause you can use it with objects too? 8- the stuff about error handling and aggregating data to me feels more of a consequence of the fact that Promises are very functional(as in functional programming) of a construct, and Javascript doesn't have very good support for functional programming, which means that there's quite a bit of stuff that you can't really do without it feeling weird or convoluted. It always feels like JS features are kinda thrown there, and don't really compose very well with each other. But hey, that's just my 2c, feel free to disagree
@dungandonuts
@dungandonuts 6 лет назад
Pika ^_^ you had the same idea as me that the last example could have been a fold/reduce! When I first saw destructuring it did remind me of Haskell's patten matching and here is the same as the x:xs pattern. It's kind of a shame that JS doesn't have a concept of monads because Async/await basically is just do notation but only for promises.
@dimaorols8143
@dimaorols8143 6 лет назад
In my opinion async/await only offer a syntactical sugar on top of promises themselves. - Writing Promise.all(users.map(user => processUser(user.id))).then().catch() is better as it would resolve items in parallel and fail on failure. - Generators can be similar if considering that every generator is pausable and can have it's own state during execution. That can be recreated with a curried function where it's inner function uses closure declarations for internal manipulation. - As for curiosity you could look at LiveScript transpiler. It doesn't use async/await and it's closer to functional programming than CoffeeScript: livescript.net/#
@TheMasterpikaReturn
@TheMasterpikaReturn 6 лет назад
Oh I forgot about Promise#all. That's most likely the best option. Generators... eh I always found them kinda clunky to use. Also I already know of livescript, and it's one of the options that I considered before learning haskell, but nowadays I can use haskell on the front-end too (either ghcjs or purescript, which is very similar), so I never looked into it again.
@artgreg2296
@artgreg2296 6 лет назад
Especially agree with your point 3. "then chaining" was meant to avoid nesting
@justvashu
@justvashu 6 лет назад
Art Greg the thing about then chaining is that it really starts to break down when you depend on the result of a previous promise or many others. Then you need to start nesting and have to get clever with the flow of code in order to pass values along or follow conditions. It also makes the code a little harder to break down into simpler units for testing because all the promises are coupled with the one that provided it’s required data. There are ways around it of course. The thing I like about async-await is that I can unit test the code without promises if it’s more practical.
@ErnestGWilsonII
@ErnestGWilsonII 6 лет назад
I see folks juggling to avoid a flat out admision that async/await is better on long complex multi-step asynchronous programs. Mixing Promise and Promise All with a main driver script that uses async-await is a huge improvement to code readability. First learn callbacks, then write everything Promise / Promise All style and then graduate to writing the main body of your program in async/await style, this is really satisfying and super readable allowing anyone following in your footsteps to easily reason about your code, a clear sign that async-await carries less technical debt.
@vlad981
@vlad981 6 лет назад
TL;DR, no it;s not useless )
@Ozziepeck11
@Ozziepeck11 6 лет назад
Vlad it’s
@u4yk
@u4yk 6 лет назад
So... Betteridge's Law, then...
@paolodisintegra
@paolodisintegra 6 лет назад
Why do we have to hate ourselves and use promises when we can enjoy some simple async await and invest our time on more fun stuff 😄
@illuminatiZ
@illuminatiZ 3 года назад
It is pure intellectualism. but when you must code and have no time, it is time to code async/await.
@smilebagsYT
@smilebagsYT 6 лет назад
First thought before watching: No, no it isn't. Let's see if I change my mind!
@smilebagsYT
@smilebagsYT 6 лет назад
Well, I didn't change my mind but it was a good look into why I believe async/await syntax is beneficial. Great video, thank you!
@benjaminmosnier
@benjaminmosnier 6 лет назад
I was exactly thinking this way... but I have to admit the last example showing recursion is very clever
@vlad981
@vlad981 6 лет назад
yeah, I think it's too much clever) We should use easiest solution possible, and async\await is definitely makes code easier to reason about.
@AngusMcIntyre
@AngusMcIntyre 6 лет назад
Iron Candy the language shouldn't be holding your hand?!? That is exactly why we have languages. Would you prefer doing it all in assembler?
@smilebagsYT
@smilebagsYT 6 лет назад
I must disagree. Async/await encourages readable code. Whether the developer decides to write convoluted, long functions is unrelated. Async/await only seems to take away the understanding of what's really happening, only until they try actually doing something with it. You need to understand promises to use async/await effectively. Syntactic sugar is syntax. Syntax which makes things easier is a good thing.
@ProgramArtist
@ProgramArtist 6 лет назад
I am not against promises and don't have any strong opinions to prefer one over the other but here is what I think about the things you said in the video: The complexity of the code is not measured only by how nested it is, it is also measured by the number of things you need to keep in mind while reading the code itself. 13:32 you said you had to think about the code and after you figured it out it felt simple. For me, a sentence like this means the code smells. I prefer the code to read like a well-written book and not like a smart poem. What I mean by that is that in well-written poems, you need to stop and think about every line and understand the meaning of it and how it contributes to the idea of the poem. In the book, on the other hand, you will read much more but the idea will be much more clear to you and you will get it faster. Also for me, a code with promises looks a lot like a code with streams (like in RX for example), and it sometimes feels like reading a very long sentence with many ideas in it, you get lost in the middle and go back to re-read from start. I prefer reading short sentences one by one and breaking the ideas apart. Probably you can refactor async/await code to promises in a good and understandable way, but it is harder to do so and there are much more ways to get it wrong.
@matthewbarbara2916
@matthewbarbara2916 6 лет назад
You said something like this one on the burger code "This code is horrible and it has a very bad architecture". Given that it would not take much of your time to polish and refactor such code, I recommend you to always show a quality code for the sake of the followers who lack the coding quality. Keep it up
@funfunfunction
@funfunfunction 6 лет назад
It's also code about burgers. :) This is example code bent to illustrate certain points. Real production code has massive amounts of noise (and is honestly often not perfect either) and would not serve to achieve the goal of the video.
@majorbadidea
@majorbadidea 6 лет назад
Fun Fun Function yes but the lets could have been consts and the formatting could have been prepared
@wonderingAroundtoNoWhere
@wonderingAroundtoNoWhere 6 лет назад
Methew Barbara i have to see the code, but i am kinda sure you are not right, because that's not how it work, you keep the noise out and focus on the topic, it is hardest things to do, i am learning my self hard way which code to use and which one not to use. And when it comes to JavaScript the whole world is up side down, because things are so inter connected, So in short they probably use the right code for the topic which they are covering.
@Sworn973
@Sworn973 6 лет назад
6:37 "it is not to bad". Everything in one big line, lambda, with nested promise with a lambda with inline if, with another promise with another inline if. Definitely is not to bad, is insanely bad. IF the main point of the away is to create better code, Yeh it works, but as everything else in programming if not used with sanity, it will end up with nightmare mess. Even in functional programming breaking down those inline nested mess will make it more clean. 15:05, return a inline calls will never be "clean". As you said, "We return the query, than we process the user" ops, Return, end of function. So it is not so clean and have traps just "await"ing for unaware people. The actual order of the inline call can be trick. Specially if you throw some lambda with recursion. if you write like you tried to say query get users process that is clean, And you return what ever is needed;
@hajimeyamasakivukelic7235
@hajimeyamasakivukelic7235 6 лет назад
Here's a missed opportunity. Throw exceptions into the mix (pun intentional), and suddenly promise-based code look much better. Also, the example code has bad separation of concerns in general, and promise-based solution tend to push you towards solving those issues as well. Overall, async/await encourages some bad patterns if you look at it carefully.
@TedHopp
@TedHopp 6 лет назад
David was struggling to find the words to laud recursion. Perhaps this (anonymous?) aphorism will do: "To iterate is human; to recurse, divine."
@bloodaid
@bloodaid 6 лет назад
This reminds me a little bit of the whole "assembly programming is better..." argument people used to have once high level languages started to appear. Async / Await are simplifiers. USE THEM!
@chanlito_
@chanlito_ 6 лет назад
click baited
@RazvanLaurus
@RazvanLaurus 6 лет назад
async / await is certainly an improvement. It doesn't require as much boilerplate as promises do (or callback style) and it makes the code easier to reason about, thus more maintainable. As for the conclusion of this episode, that functional recursion is an alternative, do keep in mind that recursion is not "safe" in JS. Not all platforms support tail call optimization, hence with long lists (high depth), there's always a risk to run out of stack.
@benbanda07
@benbanda07 6 лет назад
Where I used async/await the most, is with mongodb, when I need some arrays from differents collections (example: user, appointments, profesional and service) and if I had used promises, I would have had a "promise hell"
@funfunfunction
@funfunfunction 6 лет назад
We discussed this in the forum, and we concluded that it works fine with promises if you do the same thing that you technically do with async await, and just collect stuff in a closured variable: const displayAccountAndContacts = accountName => { let account return fetchAccountByName(accountName) .then(loadedAccount => { account = loadedAccount return fetchContactsByAccountId(account.id) }) .then(contacts => { console.log(`${account.name} (${account.id})`) contacts.forEach(contact => console.log(` - ${contact.fullname} (${contact.job_title})`)) }) .catch((error) => { console.error(error) }) } Alternatively, you can build up the result gradually: const displayAccountAndContacts = accountName => fetchAccountByName(accountName) .then(account => fetchContactsByAccountId(account.id) .then(contacts => [ contacts, account ])) .then(([ contacts, account ]) => { console.log(`${account.name} (${account.id})`) contacts.forEach(contact => console.log(` - ${contact.fullname} (${contact.job_title})`)) }) .catch((error) => { console.error(error) })
@bunglegrind1
@bunglegrind1 5 лет назад
I prefer the third way: working with asynchronous libraries such as Douglas Crockford's parseq or nodejs async. I tried to implement the example using parseq (hopefully without errors...) - For the sake of brevity, async requests are not supposed to return an error. The function returns a "requestor" - for more info check Crockford website or his latest book. pastebin.com/embed_js/ZEhSP6PU
@LoveLearnShareGrow
@LoveLearnShareGrow 6 лет назад
I absolutely love that I scrolled down to see all the comments were about READABILITY. I'm only a junior programmer, so I can't say what senior programmers will find "easy to read" but recursion (as much fun as it is to write) is *horrible* for readability. And the main thing I hate about promises is that it keeps breaking up the scope so that I have to do weird tricks to pass data from the top to the bottom. Async/await solves those problems, at least when you don't need fine grained try/catch blocks. It's usually very easy to read and very easy to pass data where it needs to go. I love it.
@GreenZ3r0
@GreenZ3r0 6 лет назад
Your db example can be a lot shorter if you use Promise all and array map. ( return Promise.all(db,query(...).map(u => processUser(u.id))) )
6 лет назад
I find generators with "co" library to be more powerful than async-await, as execution can be cancelled after some step. But 9/10 times I rather write an async function, as no additional library needed and would be easier to understand for others.
6 лет назад
Well, most libraries you can implement yourself in a rather quick time. But using something field-tested is most of the time better.
@pepkin88
@pepkin88 6 лет назад
Yes, this. And also nice and intuitive abstractions of yielding arrays and objects. Plus support for thunks, which are just old style Node functions, partially applied with Function#bind.
@julianpinn5018
@julianpinn5018 4 года назад
Conclusion: async/await results in clear and powerful code that is still readable when revisited in the future.
@allan2932
@allan2932 6 лет назад
As I see it Promises is the JS functional way of doing async programming. It can be used together with functional techniques like currying and point-free programming. I prefer this style but if you are more into imperative programming async await is probably easier to reason about. The point with the SQL example that used recursion was also that the "waitForEach" function most likely could be found in any functional library and therefore you probably wouldnt have to write it in the first place if you were doing functional programming. If you dont have to write that function then that example get easier to understand than the async await one. Also, in order to have error handling with async await you need to place it in a try catch and that is not very nice code to look at compared to a catch I think. Its true that aync await have less nesting but if you more than 1-2 levels of nesting with your promises you should probably rethink your architecture anyway
@SumTsuiTechie
@SumTsuiTechie 6 лет назад
surprise this comment didn't get a lot thumbs ups
@SimonScarfe
@SimonScarfe 6 лет назад
Great video! Is there any light at the end of the Proper Tail Calls / Tail Call Optimisation tunnel in JS-land? At the minute I'd hesitate before reviewing any code using recursion with arrays of unknown size, unless I was developing only for Safari.
@HermanWillems
@HermanWillems 6 лет назад
There is Tail Call Optimisation is a specification of ES6... Not sure about the details though jsperf.com/tco#chart=bar
@chrsolr
@chrsolr 6 лет назад
Quick question. How's easier/better to do error handling with promises? How about try/catch? Am I missing something?
@modernclics
@modernclics 6 лет назад
It's actually really simple and it encourages you to catch errors: someAsyncFunction() .then(result => {}) .catch(error => {})
@thezanke
@thezanke 6 лет назад
Pretty sure whoever wrote `waitForEach` has been dabbling with Elixir 😂Also, wont that cause a max call stack? Even if we had proper tail calls, I think that it'd blow up..
@brenton8568
@brenton8568 6 лет назад
The implementation of `waitForEach` isn't equivalent to the async/await example. In the async/await version the `processFunc` is only called for each item *after* the previous item has been processed. But the `waitForEach` version calls `processFunc` on every item in the list immediately. This is because the recursive case is calling `waitForEach` eagerly instead of lazily. This can be fixed by wrapping the `then` in a function. e.g. `processFunc(head).then(() => waitForEach(processFunc, tail))`. Alternatively, a reduce can be used and the explicit recursion avoided entirely. e.g. `const waitForEach = (processFunc, items) => items.reduce((acc, item) => acc.then(() => processFunc(item)), Promise.resolve());` This has another advantage - it returns a promise that is resolved when all of the processing is complete! (It also avoids people complaining about the potential stack overflow with recursion ;))
@AngusMcIntyre
@AngusMcIntyre 6 лет назад
Brenton Alker I believe this is incorrect. The n+1th item is only processed when the nth item has completed. This is achieved by start a continuation with .Then(). Continuations do not execute until the antecedent completes. It is not just a fancy wait. It is synonymous with Bind in the monad pattern.
@gasjack
@gasjack 6 лет назад
I had the exact same thought. In fact, I don't think the refactored example would even run, since .then() takes a function, but in the refactor, it is handed the result of calling waitForEach (which is a Promise)
@brenton8568
@brenton8568 6 лет назад
Angus, I'm not sure which part specifically you believe is incorrect. The async/await example at 09:00 behaves as you say - it only processes the n+1th item after the nth item has finished processing. But the "waitForEach" version at 12:00 will start processing all items immediately and doesn't care when they finish. As my comment says - if you want the same behaviour as async/await, you need to delay the processing by wrapping it in a function (continuation). ".then" doesn't create a continuation, it takes one and runs it, the code shown doesn't give it one it gives it a promise (which is already executing - promises are eager). Here is a repl.it session with all 4 versions, you can see the difference in behaviour in the buggy version compared to the others - repl.it/@tekerson/Is-async-await-useless
@brenton8568
@brenton8568 6 лет назад
Rasmus Vestergaard Hansen, you're right, yes, it is passing it a promise instead of a function, luckily (I guess) the spec says that if you pass anything that's not "callable", then it will just treat the identity function as the argument (ie. that step in the promise chain will just pass its value through) - www.ecma-international.org/ecma-262/6.0/#sec-performpromisethen e.g. This produces "Hi!" even though the first `.then` isn't a function. `Promise.resolve("Hi!").then(false).then(console.log);`
@AngusMcIntyre
@AngusMcIntyre 6 лет назад
Brenton Alker I see it now. Thanks for the explanation. Well spotted!
@TheMrChugger
@TheMrChugger 6 лет назад
That final recursive solution makes me feel so dumb. I mean I understand it entirely, but I'd never have dreamed of writing it like that. Beautifully done.
@maagiapall
@maagiapall 6 лет назад
One of the big reasons I much prefer the async/await version for getHamburger is this: imagine you're seeing this function for the first time, in the middle of a random codebase, no documentation, maybe the function isn't named as clearly... And you need to figure out exactly what the function returns. In the async/await example, I can scroll right down and see that it returns defaultBurger, or loadBurgers depending on the branching. In the case of promises, I have to sort of start following what's being returned at each level of indentation and slowly work my way to the end to see what's being returned. I could technically skip to the deepest level of indentation, but in that case I might miss some logic that happened before. This might take 2 seconds or 20 seconds longer, but the point is, it's time that you have to take to figure stuff out, as opposed to the async/await version which reads like a book. The more we can avoid these 2-20 second distractions, the less tired we will be 2, or 4, or 8 hours into the work day. And the more productive we will be as a result. So even if the code is only slightly more readable, to me that's a big win.
@joaofnds
@joaofnds 6 лет назад
10:18 why not: function proccessAllUsers() { const sql = 'SELECT id FROM users' db.query(sql, []) .then(users => Promise.all(users.map(proccessUser))) }
@funfunfunction
@funfunfunction 6 лет назад
Because that would change the meaning of the code example. The example illustrates sequential promise processing.
@GodOfMacro
@GodOfMacro 6 лет назад
and what about db.query(sql, []) .then(users => users.reduce((q, u) => q.then(u => processUser(u.id)), Promise.resolve()))
@funfunfunction
@funfunfunction 6 лет назад
Yep, that works great!
@sney2002
@sney2002 6 лет назад
There is an error in waitForEach which makes it run in parallel instead of sequentially. the next call to waitForEach must be inside of a function call: processFunc(head).then(() => waitForEach(processFunc, tail))
@modernclics
@modernclics 6 лет назад
I totally agree on using Promise.all despite of what the original async / await code was trying to prove. IMHO the proposed solution on the video looks unnecessarily complex. In the end Javascript is asynchronous and the most coherent way to wait for a set of promises is using Promise.all. Maybe Matt and David should have consider a different approach for the video like: "Javascript is asynchronous, don't try to make it look like it isn't" and propose simpler algorithms using promises. Disclaimer: This is not a rant, I'm a big FFF fan. :D Cheers!.
@ryoboua
@ryoboua 6 лет назад
let arr = [1,2,3,4,5,6,7,8,9] const recursionFunction = ( [head, ...tail] ) => { console.log(head) if (tail.length) return recursionFunction(tail) return } recursionFunction(arr)
@CPlayMasH_Tutoriales
@CPlayMasH_Tutoriales 6 лет назад
Maybe with simple examples promise-based code is better, but when you have complex logic with lot of edge situations to be handled, then async-await is way better for readability and productivity
@MiChAeLoKGB
@MiChAeLoKGB 6 лет назад
The only reason I find aysnc / await useless is, that my JS has to run in browser (no fancy shmancy node.js) and its not supported in IE 11 which I still have to support. At least I got my boss to agree with me and drop support for IE 10 last week, so now I just have to wait few years for IE to disappear completely and be able to use somewhat new JS stuff. Other than that, this video probably sold the saync / await even more :D
@MiChAeLoKGB
@MiChAeLoKGB 6 лет назад
Id like to, but I can't. The company I work at, well its basically only the boss, just avoids any new stuff, like SASS or Babel or any CI/CD etc. If he wont give in, I will probably just leave tho. I did get in some new things, but it was usually by me just doing it and telling him when it was one :D Thats how I partially got in SASS at least for our front-ends...
@MiChAeLoKGB
@MiChAeLoKGB 6 лет назад
Yeah, that's what I did with SASS. I really have to push in some sort of CI/CD, like buddy.works or even gitlab hooks, so the babel and SASS gets compiled automagically. The issue is, my boss likes to work on live versions on the server. If I had any real time to do so, I probably would, but he is refusing to hire somebody, because he wants us to have more work than we can comfortably handle (so you end up switching even 4 projects a day), because it keeps us on our toes :D But as I said, I will try to push in buddy or something similar and it that wont happen, Ill just probably go. I want to learn and use new stuff, not only hear/read about it, without even trying it that much, because I just don't want to see any code when I get home... I guess I'll just stop talking now...
@sanderd17
@sanderd17 6 лет назад
Nested ternary operators... no thank you, I prefer to keep my sanity.
@lnr124
@lnr124 6 лет назад
Is there a typo on line 11 of your rewrite? Should it be processFunc not processFn? Or I am reading it wrong?
@DavidWMiller
@DavidWMiller 6 лет назад
You are, it's the argument, named on line 8.
@OkanEsen
@OkanEsen 6 лет назад
Yeah but I guess the purpose of the video wasn't really about "correctnes" but rather to get the point straight and therefore more like pseudo code.
@ChrislyBear
@ChrislyBear 6 лет назад
Probably a typo.
@VanjaMk1
@VanjaMk1 6 лет назад
Yeah, that tipped me off too. A typo. Good thing I searched the comment thread before posting it ;)
@jason_v12345
@jason_v12345 6 лет назад
If a language feature obviates the need to "bother" learning something more complex, doesn't that fit the very definition of "useful"?
@funfunfunction
@funfunfunction 6 лет назад
It doesn't doesn't do that, though. If you don't understand promises, you should really not be using async / await yet,
@PeerReynders
@PeerReynders 6 лет назад
Seems some people overlook that having learnt how to wrangle promises is beneficial practice for when you later need to learn how to wrangle observables (RxJS or tc39/proposal-observable). I suspect that the recursive solution at the end was a cliffhanger to talk about for-await-of which is included in ES2018 (tc39/proposal-async-iteration). async function main() { const users = [ { id: 1, delay: 1000 }, { id: 2, delay: 300 }, { id: 3, delay: 500 } ]; for await (const x of users.map(processUser)) { console.log(`done: ${x}`); } } // Output: // start: 1 // start: 2 // start: 3 // resolve: 2 // resolve: 3 // resolve: 1 // done: 1 // done: 2 // done: 3 const processUser = ({ id, delay }) => { console.log(`start: ${id}`); return new Promise((resolve, _reject) => { fakeProcessing(resolve, id,delay) }); }; const fakeProcessing = (resolve, id, delay) => { const resolveIt = () => { console.log(`resolve: ${id}`); resolve(id); }; setTimeout(resolveIt, delay) } main();
@PeerReynders
@PeerReynders 6 лет назад
I never implied that observables are a "one size fits all" solution. I'm not Netflix: Promise to not use Promises - ES7 Observables by Brian Holt ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-DaCc8lckuw8.html I was thinking more about enriching one's toolbox, broading one's skillset to be more prepared for upcoming challenges. Most button-click examples are just a "Hello World" equivalent and not really representative of effective use cases for observables (though the throttle and debounce operations seem to be popular with click event sources; see "ReactiveX RxJS Manual Overview Flow" example) In terms of UI "drag and drop" would probably be a better example. Processing (and filtering) data coming in over one or more WebSockets at unpredictable intervals would be a much better example but would already require a some basic understanding of working with event streams. Even Ben Lesh (RxJS lead) admits that understanding observables is rarely "easy" in the beginning. ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-D7ImfM7_mcs.html "The introduction to Reactive Programming you've been missing" by Andre Staltz is one of the better introductions. Observables primarily exist to make dealing with repeating events (event streams) easier. This is accomplished by moving away from "program statements defining a sequence of steps to be taken" and moving toward "data traversing a pipeline of composed operations which transform the data by applying expressions". It's a programming style where you structure the flow of data, not the flow of control. It's a different way of composing logic that relies on composing operations and expressions rather than composing statements. Promises and observables are strangely similar even though they are different: - A promise value/error pushes through the chained handlers as soon it is settled (i.e. it's eagerly evaluated), while observable events are pushed through the operators only when at least one subscriber is listening for events (i.e. they are lazily evaluated). - A promise settling is like an "event" but by design the "stream completes" after that single event - so conceptually it is a "single event stream". Because promises can only be settled once, it is possible to retrofit imperative programming constructs in an async, await, or for-await-of style which tends sweep the promise's asynchronous nature under the rug (for better or worse). A promise handler chain clearly focuses on the sequence of composed transformations that occur when/if the value/error becomes available.
@okaybenji
@okaybenji 6 лет назад
great video! i was convinced async/await was useless, but these examples actually convinced me i was wrong. is there a way to tell, before reaching for promises, that the problem you’re working on might be one async/await is better suited to solve?
@imxd9698
@imxd9698 6 лет назад
Why not Promise.all the processUser? Promise.all(users.map(user => process(user.id)))
@joemiller1057
@joemiller1057 6 лет назад
That changes what the code does. The async await example does not launch all the calls in parallel like this would.
@LazyGod840
@LazyGod840 6 лет назад
Yes it changes the code, but for me the question is do we really have to wait for each user to process the next one? And if we dont, how would you write it with async/await? But of course, it does something else :)
@imxd9698
@imxd9698 6 лет назад
Yeah but it should.
@joemillervi
@joemillervi 6 лет назад
Im XD no the point of this is to compare async vs promise. That is difficult to do if you also change what the code does. You would be comparing apples to 🍊
@LarsGyrupBrinkNielsen
@LarsGyrupBrinkNielsen 6 лет назад
7:15 getHamburger with error handling and less nesting: const getHamburger = (server, defaultBurger) => server .hasBurgers() .then(hasBurgers => hasBurgers ? server.getMaxNumberOfBurgersPerDay() : Promise.reject()) .then(maxBurgers => getNumberOfEatenBurgersToday() < maxBurgers ? server.loadBurger() : Promise.reject()) .catch(() => Promise.resolve(defaultBurger));
@allenbythesea
@allenbythesea Год назад
I think the async / await is garbage. The small amount of help it gives is so outweighed by the extra coding work that its completely not worth it. I've seen more bugs due to unexpected behavior from this in developers.
@ovreskosolutions3992
@ovreskosolutions3992 2 года назад
async await is nothing more than a high level cpu context switching, Implicit switching is handled by the OS by a general purpose CPU scheduler and by definition anything called general purpose is not that efficient. it has nothing to do with programming syntax . 2nd async and event loops has nothing to do with promises, one (await/async) is low level architecture design with CPU scheduling in mind, javascript promises are for it''s ngine (Chrome's V8 JavaScript engine.) what async/await is for the CPU. first adopters of the async/await are languages with concurrency problems (i'm talking to you python's GIL) as a mean to ... you know ... becoming a real programming language
@toddwilson5532
@toddwilson5532 6 лет назад
Error Handling with recursion In the following example how would you get an array of errors back to the parent... ( this is from of your example in this episode ) ///////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// const processAllUsers = (users) => waitForEach( user => processUser(user), users) const waitForEach = (processFunc, [ head, ...tail]) => !head ? Promise.resolve() : processFunc( head ) .then( waitForEach( processFunc, tail ) ) .catch( (err) => { console.log(`if not caught here an unhandled error will be thrown... ${err}`) // ?? how would you add this error to an array of errors and then when "complete" get that set of errors back to the parent or main in this example ?? }) const processUser = (u) => { return new Promise ( (resolve, reject) => { console.log(`${u.name} ${u.number}`) if (u.error) reject(`ERROR - Found in - ${u.name}`) resolve() }) } let users = [ {name: 'Alpha', number: 0, error: false}, {name: 'Beta', number: 1, error: true}, {name: 'Gamma', number: 2, error: true} ] processAllUsers( users ) .then( () => console.log('No Errors') ) .catch( (err) => console.log('Caught Error - ', err.message) ) // ?? catch the array of errors here ??
@MattFarmerdotnet
@MattFarmerdotnet 6 лет назад
In my experience the one thing that is easier to program correctly using async/await is when part of your code `throw`s before you return your promise. See this example: // Common methods function getConfig(key) { throw new Error('Key Not found'); } function someAsyncMethod(data) { return Promise.resolve(data); } // Implementations function promiseVersion() { return someAsyncMethod(getConfig('someKey')); } async function asyncVersion() { return await someAsyncMethod(getConfig('someKey')); } // Show Differences // Throws an error, error handler is not called promiseVersion().then( s => console.log(s), e => console.warn(e) ); // Error handler is called asyncVersion().then( s => console.log(s), e => console.warn(e) )
@retiar2111
@retiar2111 6 лет назад
I just thought about error handling. Taking your word for nexts week episode :D
5 лет назад
I found a very useful function of async/await Let's think of this scenario: I've got a "route" treatment in express that calls an asynchronous function: The only way I found to deal with that asynchronously was passing "res" to the function in order to it to respond to the client. I HATED THIS. So I need to promisify the async function so it's the "route function" the one who responds and I don't have to pass "res" to other level. (I know I'm not quite clear so I give an example: app.get("/save", (req,res) => { saveFile(req.fileName, req.data, res) }) function saveFile(fileName, data, res) { fs.writeFile(fileName, JSON.stringify(data), (err) =>{ if(err) res.send({saved: false, err: err}); // .status(404) res.status(200).send({saved: true}); }); } I hope this'll serve for you to see my point) Once again: thanks MPJ for your great job
@voifusgaton
@voifusgaton 6 лет назад
The `processAllUsers` translation is not correct. `waitForEach` calls `processFunc` over all inputs instead of waiting for the first promise to resolve before calling it over the second input. Additionally, `waitForEach` is not generic, as it will short-circuit if you attempt to use it over an array of booleans, numbers that might be 0, possibly empty strings, or any array of possibly falsy values. Given that it behaves in the way I just described, it might as well just be defined as: `const waitForEach = (fn, vals) => Promise.all(vals.map(fn)).then(() => {});`
@pepkin88
@pepkin88 6 лет назад
I would prefer Array#reduce rather than an additional function for that. users.reduce((promise, user) => { return promise.then(() => processUser(user.id)) }, Promise.resolve()) But I would prefer yield/await syntax instead of pure promises (and LiveScript instead of JS).
@ColinRichardson
@ColinRichardson 6 лет назад
Await functions are promises, Promises can be "awaited" for.. Just use which ever makes the most sense. Only time I think it looks a little ugly is if you want to do something in parallel. const [value1, value2] = await Promise.all(asyncFunction1(someArgs1), asyncFunction2(someArgs2)); And to be honest, even then, it's very acceptable, especially if there are variables above the promise all that you need to re-use again.
@itacirgabral8586
@itacirgabral8586 6 лет назад
in sql example, waitForEach chain is serializing the processUser over the list of users. Maybe it could be made in parallel: . db.query().then(lst => Promise.all( lst.map(processUser) )) . I play with github.com/itacirgabral/blog/blob/master/futx19maio.md instead of nesting promises you can hang each step on a variable
@BennyPowers
@BennyPowers 6 лет назад
I like async await when you need an intermediate promise value in your function body ``` async write(db, token, post) { const auth = await db.authorize(token); return auth.invalid ? auth.error : await db.post(post).then(prop('id)) // await keyword here is superfluous, readability bonus is debatable } ```
@sohamchauhan4372
@sohamchauhan4372 5 лет назад
Variables in promises are scoped and not available to outer scope. For example, const user = User.find({id: 'some id'}); const admin = Admin.find({id: 'some id'}); if(user.name === admin.name) { // do something} else{ // do something else} How can this be implemented with Promises?
@kushal1
@kushal1 6 лет назад
Needless to say big fan. My comments may help in proofing that statement. Having said that, I personally don't feel the disconnect when thinking about async await. I kind of think of it as execution will jump to next line only when await is complete( Promise has resolved). So for example for loop (user of users) will execute only when await db.users is complete. It's doesn't puts me in any confusion or allusion. On the other hand, for those new to Javascript might be offered a doubt in underlying concepts. So shall we consider lucky to have worked with both Promises and Async await? Absolutely! Second, async await does offers benefits only. Be it error handling or readability. Third, video feels a bit forced one to make Promises look better. I must admit that it was hard for me to move on too initially because writing .then() seemed so much more satisfying. But that was when I had just heard or read the synchronous look of async await and not the other deep downs of error handling and stuff. Not to be missed is the debugger support in Chrome dev tools for breakpoints for myAsynFunc().then() {}call. Synchronous code lifts that off. Last, I liked the video... cause glad you brought this up and see I came up with point of feeling gratified to witness the changing syntax ( Es6) in Js land about the core stuff with a prior understanding of old concepts which newbies may not have sense of.
@nbushman
@nbushman 6 лет назад
I'm sorry, but no, the promises version did not, as you conclude, "turn out okay." Code (using async/await) which was once simple now takes careful thought and scrutiny to understand and maintain. This is exactly the kind of code that causes nasty bugs. All the hemming and hawing that you did half-way through this video suggests (I believe) that your gut agrees, but that you're reluctant to acknowledge this reality. Don't let unnecessarily-clever code enamor you. Clever code which sacrifices transparency is rarely justifiable. Although I disagree with your conclusion, I've really enjoyed the amusing and enlightening content you've put out there. Keep up the great work!
@bjornkihlberg2103
@bjornkihlberg2103 6 лет назад
async/await is an idea from Haskell. You could imagine something that is to I/O what async/await is to promises. Let's call it do/read or something along those lines. The same way async/await allows you to see on a function if it somewhere contains promises, do/read would allow you to see on a function if it somwhere contains I/O. Example async/await async f() { const x = await api.getUsers() } Example do/read do f() { const x = read console.readLine() }
@harrypatrick3126
@harrypatrick3126 3 года назад
I personally really dislike the await and async keywords. I never use await or asynch in C# or JavaScript. In JavaScript i use promises and where i want to spin something off after the linear code completes i use setTimeout. In C# i like to have a nice Task kind of thing then wait on it exactly as i want with countdown latches or whatever. I think its neater that way. I built my own dispatcher ( extended task scheduler) too for multithreading. I cant stand marking functions as async. In my opinion to the outside world a function should always execute synchronously and if you want asynchronous code the function should be called in an asynchronous way within the context of the thing calling it. This is like digital and analog. When you zoom in on digital circuitry its actually analogue in nature at that level. When you have something digital with enough states it starts to look analogue. Synchronous and asynchronous are like that. Synchronous code calling asynchronous code and asynchronous code executing lines of code synchronously. They go within each other and are interchangeable.
@FirstLast-rb5zj
@FirstLast-rb5zj 5 лет назад
The issue isn't strictly level of nesting. It's taking a block of code and having to split it. That can add nesting but it can also result in a string of a lot of functions more than you would need with it difficult to divine flow between them. This is what is meant by the spaghetti of callbacks. It's all a moot point. Promises and async/await are neither compatible nor interoperable with callbacks so you have to stay with callbacks. They both actually do things slightly differently to callbacks and if you keep using them instead of callbacks as though they're the same you'll end up writing broken code. Promises and await/async are for the parallel processing. Your wait for each function can actually break if it's not using callbacks if first come first serve. However you're just looping the users one by one.
@randyswagmonster499
@randyswagmonster499 6 лет назад
waitForEach seemed needlessly complex. If I was making an argument for promises, I'd recommend the viewer to make an array with each promise and resolve them all with Promise.all(). That way there's no need for code that's any more complex than it needs to be. That being said, I still prefer using the async/await keywords.
@hrmny_
@hrmny_ 4 года назад
This has to be a joke "promises tend to make you think about composability and what can we extract" wow you needed a helper function because it's way harder to understand then your friend says that return db.query(...).then(......) is clearer wtf
@DavideOrazioMontersinoPlus
@DavideOrazioMontersinoPlus 5 лет назад
Also ternary expressions. Might be useful sometimes, but if you are indenting your code, then your expression is too complex and plausibly could get changed in the future. Probably you'll have to change to an if / then statement (for declaring variables, for breakpoints and debugging, whatever).
@mangeshdevikar
@mangeshdevikar 6 лет назад
Thanks for sharing WaitForEach approach. This will be definitely helpful when you are coding with AWS Lambda which till date only supports nodejs6.10, that means basic promises and you cant import async await lib.
@simoneicardi3967
@simoneicardi3967 6 лет назад
[OT - Maybe an idea for next episodes] - ES6 Keyed collections: Maps, Sets, WeakMaps, WeakSets. What do you think about? Could it worth talking about them? Tnx!!
@tahoemph
@tahoemph 6 лет назад
Like others I find the burger example wanting. But for another reason. It is racy. You ask the server if it has burgers and then you do some things asynchronous to whatever the server is doing and then you assume if earlier the server has burgers it still does. This is wrong no matter how you structure the code. I think most people would read user processing better as a loop and as soon as you start attempting to emit messages in a manner separate from the messages and/or gather up a list of success/failures to be displayed the waitForEach version starts involving more complexity in the shape of closures. Maybe old lispies would like this version better but then you should rename head/tail as car/cdr then. I think you should really ask a different question from "Is async / await useless". Instead ask "when is promises best and when is async / await best". Near the end you mentioned that async / await shines when you are gather up stuff. So a sequence of code that looks like "get a, based on a get b, based on b get c, ...'. Concretely maybe 'get user, get users profile, get users avatar, etc., return the enhanced user object'. One places where promises shine is when you wan to fire off a bunch of activity and then block on all or part of it being done. I think in order to make good use of async / await you are going to have to understand how promises work and it would be criminal if you use promises not to understand when async / await makes your code look cleaner.
@gosnooky
@gosnooky 5 лет назад
Functional may be how you kids code these days, but I prefer OOP. Typescript with async/await in pure OO style is the way to go for me. It's just a more sensical approach for someone who's been using C++ and Java for 20+ years.
@MrGrokku
@MrGrokku 6 лет назад
I think there is an inverse correlation between cleverness and readability. If you had a big application in production written as the first promise example it would be hell to understand, and new developers, especially the ones with less experience, would have to be handheld for a long time before they could participate in production. Ternary operators help making that worse. In my opinion, if you have to chain function calls on either side you should just use a conditional block. On the promise examples, I think they miss the ability to return a value from inside a promise's then instead of creating and nesting another promise inside it, and also the ability to simply pass the function that will handle the next step, defined elsewhere, which would be a little more functional. Personally, I don't like "async / await", but mostly because then you have to use "try / catch" blocks which end up cluttering the code even more, but that is not an informed opinion, I haven't worked with it enough to have an opinion on the topic.
@adammoefoe
@adammoefoe 6 лет назад
Once I understood async/await and used it, I found it hard to use normal promises without hitting myself. I enjoy the synchronous look, and that I don't have to ever explicitly create promises because async guarantees promise return. The only time I use .then and .catch now is when I'm dealing with a single promise, otherwise it's try catch with async/await.
@adrianli7757
@adrianli7757 6 лет назад
When I'm trying to decide whether or not one bit of code is better than another. I always ask the question: which piece of code will take less time for a beginner to understand? Sometimes I still use Promises instead of async/await (depending on the use-case), but for most of these examples, I think it fails to show the benefits of plain Promises instead of async/await.
@illuminatiZ
@illuminatiZ 3 года назад
The promise approach is a dead-end. it seems ok but when you code hundreds of lines, you don't see your nested promises anymore. fun fun functions works on small pieces of code. With Async await you will create more function and it is much more readable.
@andzrit
@andzrit 6 лет назад
There are some differences in syntax but I thought the key difference between async/await and promises is that await is similar to generator function/yield in such that you can stop and iterate. Await will always return a promise object too, so it really seems like apples and oranges. Am I wrong...?
@andrejbartko
@andrejbartko 5 лет назад
I don't know. perhaps I'm biased. I buy it in the first example although I would write it differently. In the second example, the recursion is just easier to read for me. If I see more than 3 times async / await in the code it just gets harder to figure out the logic, while if it is done as promise chain or observable pipe it is clear.
@Misantronic
@Misantronic 6 лет назад
after working productively with async await for about a year now, I see absolutely no reason to use Promises ever again. the only case is, when a function needs to be async and has to `return new Promise(resolve => ...)`
@fishfpv9916
@fishfpv9916 4 года назад
What is your thought on combining promisies and asynchronous await. I have used it to push several network requests to an earray then calling await on the Promise.all before moving on the the next step of the function.
@hypealex
@hypealex 5 лет назад
Hi fun-fun function I would like to use your sample code in my youtube channel, I will speak in my own language to my audience so they can understand well than using english, Is that OK?
@SherazAli-ky1kn
@SherazAli-ky1kn 5 лет назад
Nicely explained. But, I was expecting you guy would draw a comparison in terms of performance. Or Its just same in both cases?
@inaccessiblecardinal9352
@inaccessiblecardinal9352 6 лет назад
It obfuscates what's actually happing. Like classes do. If it's useful, fine, but I'd rather write self descriptive code.
@sirynka
@sirynka 5 лет назад
[head, ...tali] = [0, 1, 2, 3] i kind of understand how does it works, but where can i find more info about this strange and nice looking thing?
@phimuskapsi
@phimuskapsi 6 лет назад
One nice thing about async/await is that the async function is automagically wrapped in a then/promise. This means that from a synchronous function you can call an await function and do a then and the async will return data.
@Slarti
@Slarti 5 лет назад
It's clever but my philosophy is to write code knowing I am going to need to run it through a debugger in future and for that it needs to be easily debuggable.
@microcontrolledbot
@microcontrolledbot 6 лет назад
async / await is one of the best features ever added to node. I think mysql and request packages needs to get their ass in gear and return promises when no call back function is specified so a wrapper is not needed.
@joshburgess120
@joshburgess120 6 лет назад
Functional promise library for you: Creed -- github.com/briancavalier/creed
@ekhmoi4552
@ekhmoi4552 6 лет назад
I would curse so bad if I took over a project where previous developer decided to use recursive functions instead of readable code just to feel "satisfied"
@wmhilton-old
@wmhilton-old 6 лет назад
At 14:00, won't `waitForEach` silently swallow errors generated by processFunc?
@cabc74
@cabc74 5 лет назад
Do all these "clever" things on a large codebase that will have to be maintained over years by different people and come back to tell me how bad it goes.
@ninjasakimoto4438
@ninjasakimoto4438 6 лет назад
The recursive function could've been used in the a/a version no? Big ugly ternaries doesn't scream clever to me either.
@danilocecilia7831
@danilocecilia7831 6 лет назад
oh... im sorry I didn´t get the explanation of the loadallusers, where that ProcessFn comes from?
@josecaodaglio
@josecaodaglio 6 лет назад
It is useless if you never programmed in a server or you don't know what a complex project is.
@vzolin
@vzolin 5 лет назад
So using with is almost obfuscated code is better even if it doesn't offer any performance improvement?
@gillianbc
@gillianbc 4 года назад
Sorry if this is a dumb question, but in the refactored code, line 11, what is processFn?
@jasonmcintosh2632
@jasonmcintosh2632 6 лет назад
Doesn't recusion place a big load on the stack which ends up being much slower and more resource hungry?
@MikeMcLin
@MikeMcLin 6 лет назад
It’s killing me that we are staring at this code snippet that has a glaring bug in it. "processFn" is not a function.
@ctfrancia
@ctfrancia 5 лет назад
You program for people to read what you are doing. @5:30 if I was new to the project I would be so mad. so so so mad.
@binilj04
@binilj04 6 лет назад
David is back again !!!
@ThePapanoob
@ThePapanoob 6 лет назад
Why arent you using Promise.all? This would make alot more sense in the db example
Далее
Generators in JavaScript
22:16
Просмотров 48 тыс.
荧光棒的最佳玩法UP+#short #angel #clown
00:18
ТАРАКАН
00:38
Просмотров 1,3 млн
How to ACTUALLY SHIP side projects?
23:19
Просмотров 11 тыс.
Iterators in JavaScript using Quokka.js
21:07
Просмотров 110 тыс.
Is HTMX a Joke??
32:15
Просмотров 22 тыс.
Object-Oriented Programming is Bad
44:35
Просмотров 2,3 млн
Async + Await in JavaScript, talk from Wes Bos
15:52
Просмотров 117 тыс.
荧光棒的最佳玩法UP+#short #angel #clown
00:18