async/await
Async programming = the strategy of not blocking the event loop while something (I/O, timer, fetch, etc.) finishes; in modern JS it is expressed with Promises, async/await syntax, or event emitters—under the hood they still use callbacks, but the language hides the nesting and gives you linear-looking, exception-friendly, composable code.

Async functions are default in Chrome 55. They allow you to write promise-based code as if it were synchronous, but without blocking the main thread. They make your asynchronous code less "clever" and more readable.
Async functions work like this:
async function myFirstAsyncFunction() {
try {
const fulfilledValue = await promise;
}
catch (rejectedValue) {
// …
}
}
If you use the async keyword before a function definition, you can then use await within the function. When you await a promise, the function is paused in a non-blocking way until the promise settles. If the promise fulfills, you get the value back. If the promise rejects, the rejected value is thrown.
the async keyword can be used with other function syntax:
- Arrow functions
- Object methods
- Class methods
async <script> attribute
What's the difference between the async and defer attributes of the HTML script tag? The defer attribute will asynchronously load the scripts in order.
defer <script> attribute
In JavaScript, the defer attribute is used with the <script> tag to allow the browser to continue processing the page while the script should be deferred until after the HTML parsing is complete. It is primarily used to control the order of script execution and improve page loading performance.
When a script tag has the defer attribute, it tells the browser to continue parsing the HTML document while the script is being downloaded in the background. The script will then be executed only after the HTML parsing is complete but before the DOMContentLoaded event fires.
Here's an example of using the defer attribute:
<script src="script.js" defer></script>
In the above example, the script.js file will be downloaded asynchronously while the HTML document is being parsed. However, the script execution will be deferred until after the HTML parsing is finished.
It's important to note that the defer attribute only applies to external scripts (scripts loaded from an external file using the src attribute). Inline scripts (scripts written directly within the HTML file using <script></script>) are always executed synchronously and are not affected by the defer attribute.
Using the defer attribute is beneficial when you want to ensure that scripts are executed after the document structure is fully available, potentially improving performance by allowing parallel script downloads while not blocking the rendering or interactivity of the page.
However, please be aware that the defer attribute does not guarantee the order of execution if multiple scripts with the defer attribute are present. In such cases, the scripts will be executed in the order they are encountered in the document. If script order is important, you can use the async attribute instead, which ensures the order of execution but doesn't defer execution until after HTML parsing is complete.
Native functions
- reject
- resolve
- race
- all
Pending
Fulfilled
Rejected
Asynchronous Process
Callback Pattern
an asynchronous function is called...
- JQuery.getJSON('url', function callBackFunc)
then method | Thenable Interface - then()
method to subscribe to a promise object
- indicates a successful completion of the promise
- You can chain then method callbacks:
- Each then receives the result of the previous then's return value.
//breakdown
function success(){
chargeCreditCard
function error(){}
promise.then(
success,
error);
- catch()
- The catch callback is executed when the promise is rejected
- What you provide to the reject method is up to you. A frequent pattern is sending an Error to the catch
Chaining Multiple Thens
- A promise is a special type of Object that we can use to handle asynchronous tasks. We deem them promises because we are “promised” a result at a future point in time. For example an HTTP call could complete in 200ms or 400ms, a promise will execute when resolved.
- A promise has three states, pending, resolved or rejected.
- the promise object represents the eventual completion or failure of an async operation
- promises are similar to event listeners. A promise is an object that may produce a single value some time in the future. Either a resolved value, or a reason that it's not resolved (e.g. network error)
- a promise can only succeed or fail once
- Service Worker scripts that are heavily promise-based.
function getPollResultsFromServer(pollName){
return new Promise(function(resolve, reject){
//...
request.onload = function(){
if(request.status >= 200 && request.status < 400){
resolve(request.response);
}else{
reject(new Error(request.status));
}
};
request.onerror = function(){
reject(new Error("error fetching results"));
};
})
})
var promise1 = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo');
}, 300);
});
promise1.then(function(value) {
console.log(value);
// expected output: "foo"
});
console.log(promise1);
// expected output: [object Promise]
Let’s say we have 3 Promises that depend on each other linearly: fetchBook(), formatBook(book), and print(postscript). The naïve code is:
fetchBook()
.then((book) => {
return formatBook(book)
.then((postscript) => {
return print(postscript);
});
});
The nesting is unnecessary, which simplies the code to:
fetchBook()
.then((book) => {
return formatBook(book);
})
.then((postscript) => {
return print(postscript);
});
Since these are single liners, the curly braces and return can be omitted.
fetchBook()
.then((book) => formatBook(book))
.then((postscript) => print(postscript));
But then we notice we have an identity function! We can just inline the function:
fetchBook()
.then(formatBook)
.then(print);
AJAX & Fetch
AJAX call
- url
- success
- type
Low Level Interface
\$.ajax()
\$.ajaxPrefilter()
\$.ajaxSetup()
\$.ajaxTransport()
setTimeout
account for network latency
setTimeout(() => {
console.log('Waited for 1 second');
}, milliseconds);
Button Event Handler
const btn;
btn.addEventListener('click', () => {
...
});
Error First callback
const fs = require('fs');
fs.readFile('./test.text', {encoding: 'utf-8'}, (err, data) => {
if(err) {
}
else {
console.log(data);
}
});
Helper Functions
\$.param()
\$.param({ a: [ 2, 3, 4 ] }); // "a[]=2&a[]=3&a[]=4
.serialize()
.serializeArray()
\$.ajax
\$.each
.get / .getJSON
jQuery
\$('#requestBtn').click(function () {
\$.get('./Tests/Data/JsonFiles').done(function (data) {
\$('#output').text(data);
});
});
Native
fetch('https://api.com/songs.json')
.then(function (response) {
return response.json();
})
.then(function (songs) {
console.log(songs);
});
- JSON
- localStorage only accepts strings, you must convert
localStorage.set('object', JSON.stringify(obj))
LocalStorage