본문 바로가기
TIL: Today I Learned

[TIL] 20201211 Async JavaScript

by 김알리 2020. 12. 13.

The Call Stack

Definition

  • The mechanism the JavaScript interpreter uses to keep track of its place in a script that calls multiple functions.
  • How JavaScript 'knows' what function is currently being run and what functions are called from within that function, etc.
  • Some sort of "bookmark"

How it works

  • When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function.
  • Any functions that are called by that function are added to the call stack further up, and run where their calls are reached.
  • When the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last code listing.

 

 

 

Web APIs & Single Threaded

  • JavaScript is single threaded : At any given point in time, the single JavaScript thread is running at most one line of JS code.
  • How Browsers help JavaScript with multi-thread tasks
    • Browsers come with WebAPIs that are able to handle certain tasks in the background (like making requests or setTimeout)
    • The JS call stack recognizes these Web API functions and passes them off to the browser to take care of
    • Once the browser finishes those tasks, they return and are pushed onto the stack as a callback.

 

 

 

Callback Hell

  • When a function has a possibilities of both success and failure, two callbacks can be passed into the function for the possible outcomes, success and failure.
  • This pattern can make code very deep and messy.

 

 

 

Promise

  • An object representing the eventual completion or failure orf an asynchronous operation.
  • A promise of an eventual value
  • A returned object to which you attach callbacks, instead of passing callbacks into a function.
  • Has 3 status
    • pending : waiting for the result
    • resolved : success
    • rejected : fail
  • Syntax
//creating a promise
const prom = () => {
    return new Promise((resolve, reject) => {
    	//code defining resolve/reject result
    })
}

//basic syntax
prom.then(() => {})
    .catch(() => {})
  
  
//to avoid nested promise,
prom
    .then(() => {
    	//success code
        return nextPromise
    })
    .then(() => {
    	//success code
        return nextPromise
    }).then.....
  • Return the promise that would bave been nested inside to avoid nesting.
  • Can use only one 'catch' for all the connected 'then'
  • Example : Creating a background changing function
const delayedColorChange = (color, delay) => {
    return new Promise((resolve, reject) => {
    	setTimeout(() => {
            document.body.style.backgroundColor = color;
            resolve();
        }, delay)
    })
}

delayedColocChange('red', 1000)
.then(() => delayedColorChange('orange', 1000)
.then(() => delayedColorChange('yellow', 1000)
.then(() => delayedColorChange('green', 1000)
.then(() => delayedColorChange('blue', 1000)
.then(() => delayedColorChange('indigo', 1000)

//background color changes every second, from red to indigo

 

 

 

 

Async 

Async Functions

  • A newer and cleaner syntax for working with async code.
  • Syntax "makeup" for promises

Async Keyword

  • Always returns a promise
  • Syntax
async function func() {
    return x;
}
func(); //Promise {<resolved> : x}

async function func() {
    throw new Error(y);
}
func(); //Promise {<rejected> : Error : y}

 

 

 

Await Keyword

  • Used inside of functions declared with async.
  • Await will pause the execution of the function, waiting for a promise to be resolved.
  • Only await promises that return a promise.
  • Syntax
async function func() {
    await promiseFunc1();
    promiseFunc2();
}

//promiseFunc2 waits for promiseFunc1 to be over before executing.
  • Example
async function rainbow() {
    await delayedColorChange('red', 1000);
    await delayedColorChange('orange', 1000);
    await delayedColorChange('yellow', 1000);
    await delayedColorChange('green', 1000);
    await delayedColorChange('blue', 1000);
    delayedColorChange('indigo', 1000);
}

 

 

 

Handling Errors In Async Functions

  • Use try/catch
  • Syntax
async function func() {
    try {
    	//code for resolved
    } catch {
    	//code for rejected
    }
}

 

 

 

 

* This post is a summary of Udemy Course "The Web Developer Bootcamp" by Colt Steele.