The focus of this post was to include new information from Colt Steele Web Developer Bootcamp Updated Version.
HTML: The Essentials
-The Call Stack
-WebAPIs and Single Threaded
-Callback Hell
-Promises
-The Async Keyword
-The Await Keyword
The Call Stack
The JS interpreter to keep track of its place in a script that calls multiple functions.
JS knows what function is currently being run and what functions are called from within that function.
When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function.
Any function 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.
The call stack operates on a last item in, first item out process.
WebAPIs and Single Threaded
JavaScript is single-threaded meaning it can only operate one process at a time. JavaScript can not multitask meaning it can not do more than one process at a single time.
Browsers come with Web APIs 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
Callback hell is where we end up passing a whole bunch of callbacks. The code begins to become very nested within itself which can make it hard to follow and even make the code confusing.
Callbacks are used to run code at a later point in time. They can get annoying when you need to do five or more dependent actions. Promises and Async functions is a way around using multiple callbacks.
Promises
A promise is an object representing the eventual completion or failure of an asynchronous operation.
fakeRequestPromise('yelp.com/api/coffee/page1')
.then((data) => {
console.log("It Worked!!! (page1)")
console.log(data)
return fakeRequestPromise('yelp.com/api/coffee/page2')
})
.then((data) => {
console.log("It Worked!! (page2)")
console.log(data)
return fakeRequestPromise('yelp.com/api/coffee/page3')
})
.catch((err) => {
console.log("Oh no, request failed")
console.log(err)
})
The Async Keyword
Async functions always return a promise.
If the function returns a value, the promise will be resolved with that value.
If the function throws an exception the promise will be rejected.
async function hello() {
return 'Hey guy!';
}
hello();
async function uhOh() {
throw new Error('oh no!');
}
uhOh();
The Await Keyword
Await keyword can only be used inside of functions declared with async. Await will pause the execution of the function, waiting for a promise to be resolved.
Top comments (0)