/ Gists / Promises, Await / Async, Callbacks
On gists

Promises, Await / Async, Callbacks

JavaScript

demo1.html Raw #

<!--https://www.loginradius.com/blog/engineering/callback-vs-promises-vs-async-await/-->

<!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">
            // 1 Promises - way 1

            // Promise1
            const promise1 = new Promise((resolve, reject) => {
                const condition = true;
                if (condition) {
                    setTimeout(function () {
                        resolve('Promise is resolved!'); // fulfilled
                    }, 300);
                } else {
                    reject('Promise is rejected!');
                }
            });

            // Promise2
            const promise2 = function () {
                return new Promise(function (resolve, reject) {
                    const message = `Hi, How are you!`;

                    resolve(message);
                });
            };

            // Test = chaining
            const testPromise = function () {
                promise1
                    .then(promise2)
                    .then(successMsg => {
                        console.log('Success:' + successMsg);
                    })
                    .catch(errorMsg => {
                        console.log('Error:' + errorMsg);
                    });
            };

            testPromise();

            // 2 Async / Await  = way 2
            async function testPromise2() {
                try {
                    let message = await promise1;
                    let message2 = await promise2();
                    console.log(message);
                    console.log(message2);
                } catch (error) {
                    console.log('Error:' + error.message);
                }
            }

            // we call it ...
            (async () => {
                await testPromise2();
            })();
        </script>
    </body>
</html>

promises-vs-asyncawait.html Raw #

<!--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>

callbacks.js Raw #

function getUser(userId, callback) {
    console.log('Get user from the database.');
    setTimeout(() => {
        callback({
            userId: userId,
            username: 'john'
        });
    }, 1000);
}

function getServices(user, callback) {
    console.log(`Get services of  ${user.username} from the API.`);
    setTimeout(() => {
        callback(['Email', 'VPN', 'CDN']);
    }, 2 * 1000);
}

function getServiceCost(services, callback) {
    console.log(`Calculate service costs of ${services}.`);
    setTimeout(() => {
        callback(services.length * 100);
    }, 3 * 1000);
}


getUser(100, (user) => {
    getServices(user, (services) => {
        getServiceCost(services, (cost) => {
            console.log(`The service cost is ${cost}`);
        });
    });
});