<!--https://www.javascripttutorial.net/es6/promise-chaining/-->

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Document</title>
	</head>
	<body>
		<script type="module">
			// example 1
			// async vraci vzdy promise
			async function x(n) {
				return n
			}

			// chaining
			x(10) // vstup je 10
				.then(n => n * 3) // 10 * 3 a return
				.then(console.log) // vysledek 30

			// example 2
			function getUser(userId) {
				return new Promise((resolve, reject) => {
					console.log('Get the user from the database.')
					setTimeout(() => {
						resolve({
							userId: userId,
							username: 'admin'
						})
					}, 1000)
				})
			}

			function getServices(user) {
				return new Promise((resolve, reject) => {
					console.log(`Get the services of ${user.username} from the API.`)
					setTimeout(() => {
						resolve(['Email', 'VPN', 'CDN'])
					}, 3 * 1000)
				})
			}

			function getServiceCost(services) {
				return new Promise((resolve, reject) => {
					console.log(`Calculate the service cost of ${services}.`)
					setTimeout(() => {
						resolve(services.length * 100)
					}, 2 * 1000)
				})
			}

			getUser(100)
			.then(getServices)
			.then(getServiceCost)
			.then(console.log)

			/*
            Get the user from the database.
            Get the services of admin from the API.
            Calculate the service cost of Email,VPN,CDN.
            300
            */
            
            
      // example 3 with async/await
      
			async function showServiceCost() {
				let user = await getUser(100)
				let services = await getServices(user)
				let cost = await getServiceCost(services)
				console.log(`The service cost is ${cost}`)
			}

			showServiceCost()
            
            
            
		</script>
	</body>
</html>