3 ms·
Hey gang! I've always found it easier to think through async operations with .then(), but recently decided to make the switch. Totally worth it for conciseness
by nikodunk 7y ago
Hey gang!
I've always found it easier to think through async operations with .then(), but recently decided to make the switch. Totally worth it for conciseness! I thought I'd share my learnings above.
Suggestions welcome!
- cprecioso 7y agoHey, something is wrong with your interpreter or your transpiler if you need to wrap every `async` function in a `return new Promise`. If you mark a function as `async` it will do it automatically - in fact, if you look at e.g. `nodent`'s output, it's exactly how it does it. Calling the `resolve` function instead a `then` callback like that is a mess, and totally not needed. Also, the `return` is not necessary, every function has an implicit `undefined` return if not explicitly stated. Moreover, in async functions you can take advantage of regular `try`/`catch` when awaiting; it seems you're just swallowing errors in your functions, which I guess is fine for the code you're showing. But keep in mind that a better practice is to let those function throw and catch it with a try/catch at the callsite. Lastly, when calling the functions to save and send the email, you can use `Promise.all` and parallelize them instead of running them serially, as they don't seem to depend on each other. If you're meaning to send the email only after it is saved, then you need to check the return value of the saving before that; because neither of the calls will ever fail; just return undefined.
- nikodunk 7y agoAh, excellent points. Thank you for the very carefully crafted comment. I will update once I've re-tested with these changes.
- kwxza 7y agoForgive me for this simple and unrelated question, but I'm new to JS development. This line right here, what is this? let courseId = fields.to.substring(0, fields.to.indexOf('@')); I've never seen this 'to' string method and I can't find a doc page for it. Can you explain it or point me towards a reference? Thanks
- stevula 7y agoI haven't read the article, but there's no special significant to the `to` here. It is just looking up the value of a key named `to` in an object called `fields`, using [dot notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...): const fields = { to: "foo@bar.com" }; fields.to // "foo@bar.com