Promises

Created by Haroldas Zapalskis & Aidas Klimas

Agenda

  1. Theory by Aidas
  2. Workshop by Haroldas

Why do we need promises?


fetchResource(url, function (result) {
	fetchResource(newUrl, function (result) {
		fetchResource(anotherUrl, function (result) {
			...
		}, failureCallback);
	}, failureCallback);
}, failureCallback);
			

try {
	await fetchResource(url);
	await fetchResource(newUrl);
	await fetchResource(anotherUrl);
} catch (e) {
	failureCallback(e);
}
			

Ways of creating a promise


				new Promise((resolve, reject) => resolve('Hello'))
			

Is same as:


				async () => 'Hello'
			

Is same as:


				async function () { return 'Hello'; }
			

Second and third options can not be used in all cases as sometimes we need to handle events or callbacks


				new Promise(
					(resolve, reject) => setTimeout(() => resolve('Hello'), 1000)
				)
			

States of a Promise

  • Pending: Initial state, neither fulfilled nor rejected.
  • Resolved: Operation completed successfully.
  • Rejected: Operation failed.

Using .then(), .catch() and .finally()


promise
	.then(result => {
		console.log(result); // Operation succeeded
	})
	.catch(error => {
		console.error(error); // Operation failed
	})
	.finally(result => {
		console.error(result); // always executed
	});
			

Chaining Promises


				new Promise((resolve) => resolve('Labas'))
				  .then(result => result + ' ')
				  .then(result => result + 'Orbio')
				  .then(result => result + '!')
				  .then(result => console.log(result))
				  .catch(error => console.error(error));
			

Console Output?


Labas Orbio!
				

Chaining Promises In Practice


				fetch('https://api.ipify.org?format=json')
				  .then(result => result.json())  // Operation succeeded
				  .then(result => {
						console.log(result); // Operation succeeded
				  })
				  .catch(error => {
						console.error(error); // Operation failed
				  });
			

await - Chaining Promises In A More Readable Syntax


						try {
							let response = await fetch('https://api.ipify.org?format=json')
							let json = await response.json();
							console.log(json);
						} catch (error) {
							console.error(error);
						}
					

Same as


						fetch('https://api.ipify.org?format=json')
						  .then(result => result.json())  // Operation succeeded
						  .then(result => {
								console.log(result); // Operation succeeded
						  })
						  .catch(error => {
								console.error(error); // Operation failed
						  });
					

Ways Of Rejecting Promises


				new Promise((resolve) => resolve('Labas'))

				  .then(result => throw 'a')
				  // same as
				  .then(result => new Promise((resolve, reject) => reject('a'))

				  .catch(error => console.error(error));
			

Practice round #1


						new Promise(
							(resolve, reject) => reject('some error')
						)
							.then(result => {
								console.log('success:', result);
							})
							.catch(error => {
								console.error('error:', error);
							})
					

Log output?


error: some error
				

Practice round #2


				new Promise((resolve, reject) => reject('some error'))
				  .catch(error => {
						console.error('error:', error);
				  })
				  .then(result => {
						console.log('success:', result);
				  });
			

Log output?

error: some error
success: undefined
				

Practice round #2 Fixing

Possible fix #1: Make sure catch is always at the end

						new Promise((resolve, reject) => reject('some error'))
						  .then(result => {
								console.log('success:', result);
						  })
						  .catch(error => {
								console.error('error:', error);
						  })
					
Possible fix #2: Make sure catch is always throwing the same result

						new Promise((resolve, reject) => reject('some error'))
						  .catch(error => {
								console.error('error:', error);
								throw error;
						  })
						  .then(result => {
								console.log('success:', result);
						  })
					

Workshop Incoming!

Thank You!

Questions?

Get slides from klimas.lt/slides