What is Async JavaScript?

Async(hronous) JavaScript is a form of JavaScript that involves using and coordinating multiple execution threads. These are commonly used in making API calls, which involves latency from the server-client connection.

Promises

Promises are objects that represent a pending/unknown value that will be resolved at a future time. Since the value Promises may represent can't be known at build time, chained callbacks can be used to fulfill any functionality that depends on said pending value. All documentation of Promises can found here.

Promise()

The Promise constructor takes in a callback with the parameters resolve and reject. These arguments are used to trigger all the callbacks attached to the Promise object using .then().

const getTenIn3s = () => new Promise((resolve, reject) => {
    setTimeout(() => resolve(10), 3000);
})

getTenIn3s()
	.then(n => n * 3)
	.then(console.log)

// 30

Promise.all()

Promise.all() waits for all promises in the passed in list to resolve before continuing.

Promise.all([promiseA, promiseB, promiseC])
	.then(([a, b, c]) => {
		console.log(a, b, c);
	})

Promise.prototype.then()

.then() is used to chain multiple callbacks waiting on a Promise together. The

// fetch() returns a promise
const get = (url) =>
	fetch(url)
		.then(res => {
			res.success = !!res.result;
			return res;
		});

// In another file
const fetchUsers = () => 
	get('/users')
	.then(res => {
		if (!res.success) {
			console.error('Fetch failed!');
			return;
		}
	
		return res.result;
	});

Promise.prototype.catch()

.catch() is used when reject() is called.

const rejectMeInABit = () => new Promise((resolve, reject) => 
	setTimeout(() => reject('hi'), 2000));

rejectMeInABit()
	.then((m) => console.log('LOG:', m))
	.catch((m) => console.error('ERROR:', m))

// ERROR: hi