Asynchronous
JS Event Loop
JS is a single threaded and single concurrent language and hence has a single call stack, heap, queue etc.
Call stack maintains record of function calls. Calling a function pushes onto the stack, returning pops off.
Heap: memory allocation to variables/objects.
Queue: list of messages (and their associated callback function) that need to be processed. When the call stack is empty, the callback function for the oldest message gets pushed onto the stack.
setTimeout(() => console.log("1"), 0);
console.log("2");
// Outputs 2, then 1
On the browser, there are queues for the DOM, network requests and timers; these are part of the Javascript Web API, not the language itself. Node.JS these are not available or reimplemented.
Callback Hell/The Pyramid of Doom
async1(result => {
async2(result => {
async3(result => {
async4(result => {
async5(result => {
async6(result => {
...
});
});
});
});
});
});
This may occur if the API under-fetches data: the client needs to call one API to get enough information to call another.
Promises have tried to solve this.
Promises
An object with three possible states:
- Pending
- Fulfilled; operation completed successfully
- Rejected; operation failed
somePromise
.then(someResult => {
...
return someResult;
})
.then(newResult => ...)
.catch(err => ...)
.finally(() => ...)
Async/await
Syntactic sugar over promises introduced in ES6.
By adding the async modifier to the function, the function will return a promise.
async function f() {
return 1;
}
// Or:
let g = async () => 1;
// Before ES6:
let h = () => new Promise((resolve, reject) => resolve(1));
By adding the await modifier before a promise or expression in a function (doesn’t work in global scope), it will force the function to wait for the promise to return. try/catch can be used as normal; if the promise fails, the contents of the catch statement will run.
(async () => {
const i = await f();
const j = await g();
const k = await h();
})();
// Before ES6:
f()
.then(i => g())
.then(j => h();
.then(k => {})
Modules and Dependencies
CommonJS
- One specification used for managing module dependencies
- Adopted by NodeJS
- The de-facto standard
- Browserify (or similar) required to use CommonJS in the front-end
Use either module.exports.* or exports.* to expose module’s public interface: the public interface is whatever value is assigned to module.exports.
Import the module using require().
npm
A node-specific package manger.
Use npm install --save module_name to install a package and add it to the project’s package.json file.