Promise chain

Just playing around with how promises work in vanilla JavaScript.

by Brian Cribb

HTML

<p id="my-text">Nothing yet.</p>

JavaScript

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
let myText = document.getElementById('my-text');
let arrResults = [];

function doSomething() {
	return new Promise( (resolve, reject) => {
		/*
    This Math.random stuff is just being used to simulate
    hitting some kind of API and coming back with
    success or failure.
    */
		if (Math.random() > .5) {
		  resolve("SUCCESS")
		} else {
		  reject("FAILURE")
		}
	});
}
doSomething()
	.then( result => {
		//console.log('1st Success callback: ', result);
		arrResults.push(result);
		return result;
	})
	.then( result => {
		//console.log('2nd Success callback: ', result);
		arrResults.push('Second Thing');
		return result;
	})
	.catch( result => {
		//console.log('*** Failure callback: ', result);
    arrResults = [result];
		return result;
	})
	.finally( result => {
		//console.log('*** Finally callback: ', result);
		myText.innerHTML = arrResults.join(', ');
		return result;
	});