@TheCodingTrain Daniel, beware that you properly return the expected Promise! At 4:50, your async function returns NOTHING, but the code executes anyway because the function does return a Promise internally. The issue you'd have is that the delay function gets's called, but if you expect to pass down a return value from the delay function, you would've lose that value, here. Unless the behavior is documented, you should return a value inside a promise chain. It is also important to note that promises are also recursive (DFS)! And you can still chain a promise AFTER a catch handler.
Yes. Not returning anything may cause unexpected behaviors. For example, let's say we have delay(1000) .then(() => someAsyncFunction()) .then(result => processResult(result)) ; and we want to debug "result", a naive approach would be to insert a console.log there delay(1000) .then(() => someAsyncFunction()) .then(result => console.log(result)) // debug .then(result => processResult(result)) ; but this would fail because result is not returned from the debug line (i.e. console.log returns void). It's just a good habit to either forward the resolved value, or return a transformed value (as in a pipeline). Promises are about processing data asynchronously. As a side note, even though it is a simple case, having a delay as initial example may not be the best example for demonstrating promises :) It is always best to run synchronously unless an external process is involved, usually loading something. For example, loading an image; function loadImage(url) { return new Promise((resolve, reject) => { let img = new Image(); img.onload = () => resolve(img); img.onerror = reject; img.url = url; }); } function delay(ms) { // return a function with a promise return (value) => new Promise((resolve, resject) => { if (isNaN(ms) { reject(new TypeError('Invalid timeout : ' + ms)); } else { setTimeout(() => resolve(value), ms); } }); } loadImage("path/to/image.png") .then(animateImage) // [async] function animateImage(img) { .... return img; } .then(delay(1000)) .then(fadeOutImage) // [async] function fadeOutImage(img) { .... return img; } ;
you know tho, rather than using a promise chain, you could just await those cases... so rather than writing... delay(1000) .then(() => someAsyncFunction()) .then(result => console.log(result)) // debug .then(result => processResult(result)) // result === undefined could just be rewritten as... await delay(1000) const result = await someAsyncFunction() console.log(result) await processResult(result) It is the exact same functionality with the subtle difference that "result" is now available in scope (no need to return it) this whole thing can now be wrapped up as a function like so... const dowork = async () => { await delay(1000) const result = await someAsyncFunction() console.log(result) return await processResult(result) // assumed to unwrap Promise } ... dowork().then(_ => {}).catch(_ => {}) the thing about async/await is it pretty much mitigates the need to .then() and .catch() entirely. Promise chaining (while fine in some cases, like fetch(..).then(res =>res.json()) as a kind of map) is actually really awkward for complex control flow. The retention of variables in scope is a subtle but powerful feature that significantly removes complexity around conditional control flow. making things easier overall.
Async / await is not yet available in all browsers, but Promises are (either natively or through a polyfill). Besides, I prefer having chainable .then and a .catch (or multiple .catch) instead of wrapping all the awaiting functions (i.e. promises) inside a try...catch block. It's not because a language offers some syntax sugar that it becomes the best solution every time.
-Await, delay, time. -Await...... Delay........ Time....! (pause to ponder) -Then I can return. This is one of the most philosophically deep statements I've ever heard! 3:31
I find it ironic that the modifier is "async" when what it effectively does is causes promises to operate synchronously... i.e. blocking. Or maybe I'm failing to understand. Keep up the great work!
Hi. A dumb question probably, how does js deals with different return values from different blocks (if, for, function) returns ?? Does the function not stops execution when it encounters a return statement ? Thanks
shadowalker101 depends on what you want to work with. In real world web applications using async/await won’t be a great idea because older browsers will hate it, but if you’re just doing it for yourself you could go either way
no, got that fail again ._. i made it the same but just with my promise function(axios post) but i only got (Promise { }) back, console.log before returning val works
The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically. javascript.info/async-await
@TheCodingTrain Daniel, beware that you properly return the expected Promise! At 4:50, your async function returns NOTHING, but the code executes anyway because the function does return a Promise internally. The issue you'd have is that the delay function gets's called, but if you expect to pass down a return value from the delay function, you would've lose that value, here. Unless the behavior is documented, you should return a value inside a promise chain.
It is also important to note that promises are also recursive (DFS)! And you can still chain a promise AFTER a catch handler.
Should it have been: return await delay(time); ?
Yes. Not returning anything may cause unexpected behaviors. For example, let's say we have
delay(1000)
.then(() => someAsyncFunction())
.then(result => processResult(result))
;
and we want to debug "result", a naive approach would be to insert a console.log there
delay(1000)
.then(() => someAsyncFunction())
.then(result => console.log(result)) // debug
.then(result => processResult(result))
;
but this would fail because result is not returned from the debug line (i.e. console.log returns void). It's just a good habit to either forward the resolved value, or return a transformed value (as in a pipeline). Promises are about processing data asynchronously.
As a side note, even though it is a simple case, having a delay as initial example may not be the best example for demonstrating promises :) It is always best to run synchronously unless an external process is involved, usually loading something. For example, loading an image;
function loadImage(url) {
return new Promise((resolve, reject) => {
let img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.url = url;
});
}
function delay(ms) {
// return a function with a promise
return (value) => new Promise((resolve, resject) => {
if (isNaN(ms) {
reject(new TypeError('Invalid timeout : ' + ms));
} else {
setTimeout(() => resolve(value), ms);
}
});
}
loadImage("path/to/image.png")
.then(animateImage) // [async] function animateImage(img) { .... return img; }
.then(delay(1000))
.then(fadeOutImage) // [async] function fadeOutImage(img) { .... return img; }
;
Thanks for all this info, I've pinned this thread!
you know tho, rather than using a promise chain, you could just await those cases... so rather than writing...
delay(1000)
.then(() => someAsyncFunction())
.then(result => console.log(result)) // debug
.then(result => processResult(result)) // result === undefined
could just be rewritten as...
await delay(1000)
const result = await someAsyncFunction()
console.log(result)
await processResult(result)
It is the exact same functionality with the subtle difference that "result" is now available in scope (no need to return it)
this whole thing can now be wrapped up as a function like so...
const dowork = async () => {
await delay(1000)
const result = await someAsyncFunction()
console.log(result)
return await processResult(result) // assumed to unwrap Promise
}
...
dowork().then(_ => {}).catch(_ => {})
the thing about async/await is it pretty much mitigates the need to .then() and .catch() entirely. Promise chaining (while fine in some cases, like fetch(..).then(res =>res.json()) as a kind of map) is actually really awkward for complex control flow. The retention of variables in scope is a subtle but powerful feature that significantly removes complexity around conditional control flow. making things easier overall.
Async / await is not yet available in all browsers, but Promises are (either natively or through a polyfill). Besides, I prefer having chainable .then and a .catch (or multiple .catch) instead of wrapping all the awaiting functions (i.e. promises) inside a try...catch block.
It's not because a language offers some syntax sugar that it becomes the best solution every time.
The philosophical depth of those farewells where he says "see you in the next video, maybe, maybe not" is incredible.
-Await, delay, time.
-Await...... Delay........ Time....! (pause to ponder)
-Then I can return.
This is one of the most philosophically deep statements I've ever heard!
3:31
After 10+ videos on Async/Await, this is the first one to really click for me. Thanks a bunch!
thank you for teaching to people who dont have money to pay a university you're helping many people like me
WE'RE @ ES8 ALREADY?!?!?!?!?!?! I'm not ready xD
yea, this is the best programming tutor hav met on youtube. Kip it up sir,
ur not boring like other I really like your video ur helpful thanks coding train (:
async/await are exactly what I have always wanted. Why didn’t I learn these earlier. Goodbye chains of 50 then
'Chains of 50'!.
I like your clear pronunciation.
So many likes in every async await tutorial. So many people understanding; I feel totally left out
You were right, this does seem a lot nicer to me :)
Love this episode, Dan!
love the passion man. thank you
I like this a lot more than a bunch of thens.
I love coding train
didn't quite understand async/await by that video. I think the example video will clarify things and I'll hopefully be able to understand then.
Yes, try part 2 (linked in video description and let me know!)
I find it ironic that the modifier is "async" when what it effectively does is causes promises to operate synchronously... i.e. blocking. Or maybe I'm failing to understand. Keep up the great work!
The blocking only happens inside the async function itself! But when you call the async function it happens asynchronously! (if that makes sense)
Hi. A dumb question probably, how does js deals with different return values from different blocks (if, for, function) returns ?? Does the function not stops execution when it encounters a return statement ? Thanks
Best teacher
You should be more confident about your work, your videos are awesome!
is async and await the same as the ordinary callback function ?
How many active timers can a Javascript program have? What if you need more than one? Btw- your tutorials are excellent!
really nice way to teach
Amazing brother!
You are my hero
I think You are such an amazing person :)
How about this:
async delayES8(time) {
try {
await delay(time);
createP('hello');
} catch (err) {
console.error(err);
}
}
Embed your .then, .catch into the async function.
Too short! hehehehe
Nice video, I really like the didactic way in which you explain things :)
Thank you! Very useful!
Crikey, not sure whether I should spend the time learning promises or just move straight onto async/await =0
shadowalker101 depends on what you want to work with. In real world web applications using async/await won’t be a great idea because older browsers will hate it, but if you’re just doing it for yourself you could go either way
Well they're sort of part of the same thing.
Thx man, you helped a lot!
no, got that fail again ._. i made it the same but just with my promise function(axios post) but i only got (Promise { }) back, console.log before returning val works
I love how he gives up on his example and tells you to just skip this video not even halfway through the video XD
I don't get how this works. DelayES8 function returns nothing, how can you call a function on it? Does await returns it behind the scenes?
The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically.
javascript.info/async-await
Please do a tetris coding challenge.
How can I "await" an Observable?
Where you coding?
so its looks like Exception ??
personally i prefer async() module
"you can't just use 'await' anywhere in your code".... of course javascript wouldn't allow something to be that easy.
Good
I don't understand why you are making videos about subjects you don't fully understand yourself yet.
He exactly understand that
More drama than coding.
137 137th view
You gave such a bad example.
You missed all the benefits of async/await
I agree this one isn’t such a good example. Did you watch the next one linked in description? I think it’s a bit better?