Welcome to Discussion #3!

CS 160 · User Interface Design and Development · Summer 2024


Do Now: Pull up last weeks activity and attempt some of the later parts: here


Back to index

Agenda

  • Async Javascript

Sync Javascript

Run line by line

Scheduling

addEventListener
- schedules code to be executed later, typically on an action. It doesn't get run right away!

This is called a callback function

Call me back

  • We make a call to (for example) an api asking for data
  • The api doesn't have it immediately ready, but promises to send it to us
  • We have to define behavior for when the api 'calls us back'

Example callback handling

decoding .WAV file data with the Web Audio API

Simple Example

setTimeout

After 1000 milliseconds, the code we schedule runs

Activity time

Call me back in 10 minutes after you've poked around some callback examples!

Tim's codepen

Example solution

Callback Hell

When async code depends on prior asynchronous code... it gets messy

The last line was about the very first callback delay

Super nested

So what .then() ?

Promise chaining

When a promise resolves we can call .then() on it to run our callback

Does this help?

What about data?

But (a)wait! There's more!


                            function countDown() {
                                console.log("three...");
                                return sleep(1000).then(() => {
                                    console.log("two...");
                                    return sleep(1000);
                                }).then(() => {
                                    console.log("one...");
                                    return sleep(1000);
                                });
                            }
            
                            countDown().then(() => {
                                console.log("Happy New Year!");
                            });
                            

                                async function countDown() {
                                    console.log("three...");
                                    await sleep(1000);
                                    console.log("two...");
                                    await sleep(1000);
                                    console.log("one...");
                                    await sleep(1000);
                                }
            
                                countDown().then(() => {
                                    console.log("Happy New Year!");
                                });
                            

Try and catch this!

Sometimes the result of a promise is an error :(

They can occur due to various reasons like invalid input, network issues, or unexpected behavior.

Try and catch this!

We don't want to crash our program if there's an error.

How do we handle this?

Multiple lines potentially cause an error...

Async Activity

Thank you!


Other resources: