본문 바로가기
Web Development/JavaScript

27. Async JavaScript

by 사향낭 2022. 1. 4.

273. Call Stack

 

- A stack data structure that stores information about the active subroutine of a computer program.

- Subroutines are stacked in call stack in execution order.

* 실행 순서대로 subroutine들이 call stack에 쌓인다.

 

 

 

274. WebAPIs & Single Threads

 

- JavaScript is a single-threaded language because of only one call stack (one line execution at a time).

- Thus, if we send our data to a server for example, we have to wait for a while to complete the "SAVE" instruction, so everything is stopped below the "SAVE" instruction. (of course, JavaScript is a procedural language)

- The JS call stack recognizes Web API functions (such as setTimeout), let the browser know these functions are Web API functions.

- After the browser finishes those tasks, they return and are pushed onto the stack as a callback.

* 싱글 쓰레드 언어인 JavaScript는 browser를 이용해 시간이 걸리는 subroutine을 넘길 수 있다.

 

 

275. Callback Hell

 

- callback of callback of callback of callback of ... It's looking crazy.

 

const delayedColorChange = (color, delay, doNext) => {
    setTimeout(() => {
        document.body.style.backgroundColor = color;
        doNext & doNext();
    }, delay)
}

delayedColorChange('red', 1000, () => {
    delayedColorChange('yellow', 1000, () => {
        delayedColorChange('orange', 1000)
    })
})

 

 

276 - 279. Promise

 

- To solve the callback hell problem, we can "promise".

- The promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

- The callback function of then method is executed after resolved.

- The callback function of catch method is executed after rejected.

 

const delayedColorChange = (color, delay) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (Math.random() < 0.7) {
                document.body.style.backgroundColor = color;
                resolve("This is resolved");
            }
            reject("This is failed uu");
        }, delay)
    })
}

delayedColorChange('red', 1000)
    .then(() => delayedColorChange('yellow', 1000))
    .then(() => delayedColorChange('orange', 1000))
    .catch((reason) => console.log(reason));

 

 

280. The Async Keyword

 

- Async function returns a promise object which is already resolved, or rejected.

- resolved with the return value.

- rejected with the thrown value.

 

// returns resolved promise with the data
anync function asyncResolvedFunction(data) {
	return data;
}
// returns rejected promise with the data
async function asyncRejectedFunction(data) {
	throw data;
}

 

 

281. Await Keyword

 

- Await keyword is only used in Async function.

- It waits until the returned promise is resolved or rejected.

- It returns the data (the paramter of resolve, or reject function.

 

const delayedColorChange = (color, delay) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            document.body.style.backgroundColor = color;
            resolve("This is resolved");
        }, delay)
    })
}

delayedColorChange('red', 1000)
	.then(() => delayedColorChange('yellow', 1000))
	.then(() => delayedColorChange('orange', 1000))
// Equivalent to
const delayedColorChange = (color, delay) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            document.body.style.backgroundColor = color;
            resolve("This is resolved");
        }, delay)
    })
}

async function delayedColorsChange() {
    await delayedColorChange('red', 1000);
    await delayedColorChange('yellow', 1000);
    await delayedColorChange('orange', 1000);
}
delayedColorsChange();

 

 

282. Handling Errors in Async Functions

 

const delayedColorChange = (color, delay) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            document.body.style.backgroundColor = color;
            resolve();
        }, delay)
    })
}

async function tryAndCatch() {
    try {
        let data = delayedColorChange('red', 1000);
    } catch (e) {
        console.log("CAUGHT AN ERROR");
    }
}

 

'Web Development > JavaScript' 카테고리의 다른 글

29. Prototypes, Classes, & OOP  (0) 2022.01.15
28. AJAX and API's  (0) 2022.01.05

댓글