javascript Flashcards
how do we handle asynchronous code in javascript
We have a few different ways to approach asynchronous code, callbacks for example, but Other concepts are async/await and Promises. Javascript is single-threaded so has no ability to manage threads the way C# and C++ do. Javascript runs synchronously.
what is a promise in javascript?
A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
What are the states that a promise can be in?
Pending: a state where the promise is neither rejected nor fulfilled. (this is the state it is in when we first call it)
Fulfilled: a state where all’s well and a resolved value can be used by our code.
Rejected: a state where something went wrong and there is an error that needs to be dealt with.
when is a promise most often used ?
when making API calls we use the helper object called a promise to inform the browser that the second, async task has finished.
What does promise handling look like? include then and catch
timeMachine() .then(parseTime) .then(timePassed => { console.log(timePassed); --> OUTPUT: DOES NOT RUN }) .catch(err => { console.log(err); --> OUTPUT: [Error: ms is less than 1 second promise rejected!] });
Why do we have asynchronous code?
Things aren’t all happening at the same time, they are actually being broken down into smaller parts, time-slice is used to do bits of each task. Threads are built into hardware to allow software developers to code. A thread is a chunk of memory and other state information about an executable thats running.
What does synchronous code mean?
synchronous means that each thing has to be complete before the next can start. Ie in a function call, everything in that function call must be complete before the next function call can begin running.
What is asynchronous code?
asynchronous code is the ability to do 2 things at the same time. We use asynchronous code to allow the browser to keep executing code while something else is happening- usually a call to an external API.
what is callback hell?
nesting callback functions to deliver asynch functionaility, its aweful and promises are a way to resolve this
What is async await
functionaly it is no diferent to a promise, however it looks more synchronous in the way its written.