Notes on JS promises


(this notes are probably incomplete)


Create a promise

new Promise(function(resolve, reject){});
new Promise((resolve, reject) => {});

// Example
function divide(x, y) {
	return new Promise((resolve, reject) =>{
		if(y != 0) {
			resolve(x/y);
		}else{
			reject(Error("Can't divide 0"));
		}
	});
}


Execute and error control

function doPromiseDivide(x, y){
	divide(x, y)
		.then(
			function onSuccess(result) {
				console.log('Result: ' + result);
				// throw Error("Error from onSuccess block generated");
			},
			function onError(error) {
				console.log('Error: ' + error.message);
				// throw Error("Error from OnError block generated");
			}
		)
		.catch(
			function(error) {
				console.log(error.message);
			}
		);
}
  • If we execute doPromiseDivide(5,3) the onSuccess is called and it prints 1.33333…
  • If we execute doPromiseDivide(5,0) the onError is called and we get ‘Error: Can’t divide 0’
  • The catch block executes if there is an error that wasn’t caught. In this case it only executes when there is a throw in the onSuccess function or onError function. But if we delete the onError function and a error is thrown by dividing by 0 then the catch blocks executes. Example:
function doPromiseDivideWithoutOnError(x, y){
	divide(x, y)
		.then(
			function onSuccess(result) {
				console.log('Result: ' + result);
			}
		)
		.catch(
			function(error) {
				console.log('Catch block executed because there is not a onError function on then');
				console.log(error.message);
			}
		);
}

doPromiseDivideWithoutOnError(4,0);

You probably want to catch errors from the promise itself in the onError block, and errors thrown in the then with a catch block.


Promise behavior

A promise is executed when is created, even if you don’t pass the params resolve, reject. So even if it doesn’t have a .then the promise is executed. And it doesn’t need to execute resolve neither reject. Example:

function alertPromise(text){
	return new Promise((resolve, reject) =>{
		console.log(text);
	});
}

alertPromise("This promise never execute resolve or reject");

This will execute the console.log


Finally block

function doPromiseDivide(x, y) {
	divide(x, y)
		.then(
			function onSuccess(result) {
				console.log('Result: ' + result);
				//throw Error("Error from onSuccess block generated");
			},
			function onError(error) {
				console.log('Error: ' + error.message);
				//throw Error("Error from OnError block generated");
			}
		)
		.catch(
			function(error) {
				console.log(error.message);
			}
		)
		.finally(
			function() {
				console.log('This block is always executed');
			}
		);
}