├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── feature_request.md │ └── quizzes.md └── pull_request_template.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md └── src ├── 01-promise-basics ├── 01-promise-basics-reject.js └── 01-promise-basics-resolve.js ├── 02-promise-chain ├── 02-callback-hell.js ├── 02-promise-chain-finally.js ├── 02-promise-chain-pizza.js ├── 02-promise-chain-rethrow.js ├── 02-promise-chain-return-promise.js ├── 02-promise-chain-return-value.js ├── 02-promise-chain-throw-error.js ├── 02-promise-chain.js ├── 02-promise-handle-reject-catch.js ├── 02-promise-handle-reject-then.js ├── 02-promise-not-a-chain.js └── 02-simple-promise-handling.js ├── 03-async-await ├── 03-async-await-basics.js ├── 03-async-await-error-handling.js └── 03-async-await-pizza-hub.js ├── 04-promis-apis ├── 04-promise-all-settles.js ├── 04-promise-all.js ├── 04-promise-any.js ├── 04-promise-race.js └── 04-promise-resolve.js ├── callback ├── index.html └── main.js ├── common-mistakes ├── index.html └── main.js ├── index.html ├── js-sync-async ├── async_1.js ├── async_2.js ├── async_3.js ├── index.html └── index.js └── tasks ├── answers.md └── readme.md /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [atapas] 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/quizzes.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: QUIZZES 3 | about: Template to request adding quizzes 4 | title: "[New Quiz Request]" 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | # What are you trying to contribute? 11 | 12 | TBA 13 | 14 | # If you are adding QUIZZES 15 | - Make sure it is well tested. 16 | - Please provide the answer in the answer.md file with a proper sequence number 17 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | # Description 2 | 3 | Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. 4 | 5 | Fixes # (issue) 6 | 7 | ## Type of change 8 | 9 | Please delete options that are not relevant. 10 | 11 | - [ ] Bug fix (non-breaking change which fixes an issue) 12 | - [ ] New feature (non-breaking change which adds functionality) 13 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) 14 | - [ ] This change requires a documentation update 15 | 16 | # How Has This Been Tested? 17 | 18 | Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration 19 | 20 | - [ ] Test A 21 | - [ ] Test B 22 | 23 | **Test Configuration**: 24 | * Firmware version: 25 | * Hardware: 26 | * Toolchain: 27 | * SDK: 28 | 29 | # Checklist: 30 | 31 | - [ ] My code follows the style guidelines of this project 32 | - [ ] I have performed a self-review of my own code 33 | - [ ] I have commented my code, particularly in hard-to-understand areas 34 | - [ ] I have made corresponding changes to the documentation 35 | - [ ] My changes generate no new warnings 36 | - [ ] I have added tests that prove my fix is effective or that my feature works 37 | - [ ] New and existing unit tests pass locally with my changes 38 | - [ ] Any dependent changes have been merged and published in downstream modules 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | tapas.adhikary@gmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | When contributing to this repository, please first discuss the change you wish to make via issue, 4 | email, or any other method with the owners of this repository before making a change. 5 | 6 | Please note we have a code of conduct, please follow it in all your interactions with the project. 7 | 8 | ## Pull Request Process 9 | 10 | 1. Ensure any install or build dependencies are removed before the end of the layer when doing a 11 | build. 12 | 2. Update the README.md with details of changes to the interface, this includes new environment 13 | variables, exposed ports, useful file locations and container parameters. 14 | 3. Increase the version numbers in any examples files and the README.md to the new version that this 15 | Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/). 16 | 4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you 17 | do not have permission to do that, you may request the second reviewer to merge it for you. 18 | 19 | ## Code of Conduct 20 | 21 | ### Our Pledge 22 | 23 | In the interest of fostering an open and welcoming environment, we as 24 | contributors and maintainers pledge to making participation in our project and 25 | our community a harassment-free experience for everyone, regardless of age, body 26 | size, disability, ethnicity, gender identity and expression, level of experience, 27 | nationality, personal appearance, race, religion, or sexual identity and 28 | orientation. 29 | 30 | ### Our Standards 31 | 32 | Examples of behavior that contributes to creating a positive environment 33 | include: 34 | 35 | * Using welcoming and inclusive language 36 | * Being respectful of differing viewpoints and experiences 37 | * Gracefully accepting constructive criticism 38 | * Focusing on what is best for the community 39 | * Showing empathy towards other community members 40 | 41 | Examples of unacceptable behavior by participants include: 42 | 43 | * The use of sexualized language or imagery and unwelcome sexual attention or 44 | advances 45 | * Trolling, insulting/derogatory comments, and personal or political attacks 46 | * Public or private harassment 47 | * Publishing others' private information, such as a physical or electronic 48 | address, without explicit permission 49 | * Other conduct which could reasonably be considered inappropriate in a 50 | professional setting 51 | 52 | ### Our Responsibilities 53 | 54 | Project maintainers are responsible for clarifying the standards of acceptable 55 | behavior and are expected to take appropriate and fair corrective action in 56 | response to any instances of unacceptable behavior. 57 | 58 | Project maintainers have the right and responsibility to remove, edit, or 59 | reject comments, commits, code, wiki edits, issues, and other contributions 60 | that are not aligned to this Code of Conduct, or to ban temporarily or 61 | permanently any contributor for other behaviors that they deem inappropriate, 62 | threatening, offensive, or harmful. 63 | 64 | ### Scope 65 | 66 | This Code of Conduct applies both within project spaces and in public spaces 67 | when an individual is representing the project or its community. Examples of 68 | representing a project or community include using an official project e-mail 69 | address, posting via an official social media account, or acting as an appointed 70 | representative at an online or offline event. Representation of a project may be 71 | further defined and clarified by project maintainers. 72 | 73 | ### Enforcement 74 | 75 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 76 | reported by contacting the project team at [tapas.adhikary@gmail.com](tapas.adhikary@gmail.com). All 77 | complaints will be reviewed and investigated and will result in a response that 78 | is deemed necessary and appropriate to the circumstances. The project team is 79 | obligated to maintain confidentiality with regard to the reporter of an incident. 80 | Further details of specific enforcement policies may be posted separately. 81 | 82 | Project maintainers who do not follow or enforce the Code of Conduct in good 83 | faith may face temporary or permanent repercussions as determined by other 84 | members of the project's leadership. 85 | 86 | ### Attribution 87 | 88 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 89 | available at [http://contributor-covenant.org/version/1/4][version] 90 | 91 | [homepage]: http://contributor-covenant.org 92 | [version]: http://contributor-covenant.org/version/1/4/ 93 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Tapas Adhikary 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Promise Interview Ready - A New Way to Learn. 2 | 3 | Please join me to learn JavaScript Promise in a new way. This repository contains all the source code and examples used in the [Demystifying JavaScript Promise Series](https://blog.greenroots.info/series/javascript-promises). It will help a beginner with many examples to understand the promises and get ready for the interview questions. You can also catch up with the video series from my [YouTube Channel](https://www.youtube.com/watch?v=pIjfzjsoVw4&list=PLIJrr73KDmRyCanrlIS8PEOF0kPKgI8jN). 4 | 5 | > 🏗️ This repo is Work In Progress at this time. We appreciate you follow, use, and contribute to it. Liked the work so far? Please give it a star(⭐) 6 | 7 | # Many Thanks to all the `Stargazers` who has supported this project with stars(⭐) 8 | 9 | [](https://github.com/atapas/promise-interview-ready/stargazers) 10 | 11 | ## Content 12 | - [JS Sync Async](https://github.com/atapas/demystifying-javaScript-promise/tree/main/src/js-sync-async) 13 | - [Promise Basics](https://github.com/atapas/demystifying-javaScript-promise/tree/main/src/01-promise-basics) 14 | - [Promise Chaining](https://github.com/atapas/demystifying-javaScript-promise/tree/main/src/02-promise-chain) 15 | - [Async/Await](https://github.com/atapas/promise-interview-ready/tree/main/src/03-async-await) 16 | - [Promise API Methods](https://github.com/atapas/promise-interview-ready/tree/main/src/04-promis-apis) 17 | - [Common Mistake](https://github.com/atapas/promise-interview-ready/tree/main/src/common-mistakes) 18 | - [QUIZZES - Practice and Fun](https://github.com/atapas/promise-interview-ready/tree/main/src/tasks/readme.md) 19 | 20 | ## Learn 21 | - [Synchronous vs Asynchronous JavaScript](https://www.freecodecamp.org/news/synchronous-vs-asynchronous-in-javascript) 22 | - [JavaScript Promises - Explain Like I'm Five](https://blog.greenroots.info/javascript-promises-explain-like-i-am-five) 23 | - [JavaScript Promise Chain - The art of handling promises](https://blog.greenroots.info/javascript-promise-chain-the-art-of-handling-promises) 24 | - [JavaScript async and await - in plain English, please](https://blog.greenroots.info/javascript-async-and-await-in-plain-english-please) 25 | - [Introducing PromiViz - visualize and learn JavaScript promise APIs](https://blog.greenroots.info/introducing-promiviz-visualize-and-learn-javascript-promise-apis) 26 | - [6 Common mistakes in using JavaScript Promises](https://blog.greenroots.info/common-mistakes-in-using-javascript-promises) 27 | 28 | ## Contribute 29 | Please contribute to this project by making it better. You can improve the doc, add examples. The majority of the contributions we are looking for is in the areas of more QUIZZES related to JavaScript Async Programming and Promises. Here is the current state of it: [QUIZZES](https://github.com/atapas/promise-interview-ready/tree/main/src/tasks/readme.md) 30 | 31 | -------------------------------------------------------------------------------- /src/01-promise-basics/01-promise-basics-reject.js: -------------------------------------------------------------------------------- 1 | // 1. Create the promise 2 | let promise = new Promise(function (resolve, reject) { 3 | setTimeout(function () { 4 | // Reject it as the disaster happend. 5 | reject( 6 | new Error( 7 | "Jack fell down and broke his crown. And Jill came tumbling after." 8 | ) 9 | ); 10 | }, 2000); 11 | }); 12 | 13 | // 2. Inform grandparents 14 | // but this time we are using the .catch 15 | const grandParentsCooking = () => { 16 | promise.catch(function (error) { 17 | console.log(`OMG!!! ${error.message}`); 18 | }); 19 | }; 20 | 21 | // 3. Call the function 22 | grandParentsCooking(); 23 | -------------------------------------------------------------------------------- /src/01-promise-basics/01-promise-basics-resolve.js: -------------------------------------------------------------------------------- 1 | // 1. Create a Promise to fetch the water 2 | let promise = new Promise(function (resolve, reject) { 3 | // Pretend a delay of 2 sec to fetch it! 4 | setTimeout(function () { 5 | // Fetched the water. Let's resolve the promise 6 | resolve("Hurray! Fetched the Water."); 7 | }, 2000); 8 | }); 9 | 10 | // 2. Function to Set up the handler to handle a promise result. 11 | // It is to inform the grandparents when the result is available. 12 | const grandParentsCooking = () => { 13 | // The handler function to handle the resolved promise 14 | promise.then(function (result) { 15 | // Fetched the water. Now grandparents can start the cooking 16 | console.log(`cooking rice with the ${result}`); 17 | }); 18 | }; 19 | 20 | // 3. Calling the function to activate the set up. 21 | grandParentsCooking(); 22 | -------------------------------------------------------------------------------- /src/02-promise-chain/02-callback-hell.js: -------------------------------------------------------------------------------- 1 | const FETCH_SHOP_ID_DELAY = 1000; 2 | const FETCH_PIZZA_DETAILS_DELAY = 1500; 3 | const FETCH_BEVERAGES_DETAILS_DELAY = 1000; 4 | const CREATE_ORDER_DELAY = 2000; 5 | 6 | function query(endpoint, callback) { 7 | if (endpoint === `/api/pizzahub/`) { 8 | setTimeout(function(){ 9 | const response = { 10 | 'shopId': 's-123' 11 | }; 12 | callback(response); 13 | }, FETCH_SHOP_ID_DELAY); 14 | } else if (endpoint.indexOf('/api/pizzahub/pizza/') >=0) { 15 | setTimeout(function(){ 16 | const response = { 17 | pizzas: [ 18 | { 19 | 'type': 'veg', 20 | 'name': 'margherita', 21 | 'id': 'pv-123' 22 | }, 23 | { 24 | 'type': 'nonveg', 25 | 'name': 'chicken cheese', 26 | 'id': 'pnv-124' 27 | } 28 | ] 29 | }; 30 | callback(response); 31 | }, FETCH_PIZZA_DETAILS_DELAY); 32 | } else if (endpoint.indexOf('/api/pizzahub/beverages') >=0) { 33 | setTimeout(function(){ 34 | const response = { 35 | 'id': 'b-10', 36 | 'beverage': 'cola' 37 | }; 38 | callback(response); 39 | }, FETCH_BEVERAGES_DETAILS_DELAY); 40 | } 41 | } 42 | 43 | const createOrder = (payload) => { 44 | setTimeout(function(){ 45 | const {type, name, beverage} = payload; 46 | console.log(`The ${type} ${name} pizza order with ${beverage} has been placed successfully.`); 47 | }, CREATE_ORDER_DELAY); 48 | } 49 | 50 | function orderPizza(type, name) { 51 | 52 | // Query the pizzahub for a store 53 | console.log('Locating the nearby shop...'); 54 | query(`/api/pizzahub/`, function(result, error){ 55 | if (!error) { 56 | let shopId = result.shopId; 57 | console.log(`Got the Shop Id as ${shopId}`); 58 | // Get the store and query pizzas 59 | console.log('Querying for the pizzas...'); 60 | query(`/api/pizzahub/pizza/${shopId}`, function(result, error){ 61 | if (!error) { 62 | let pizzas = result.pizzas; 63 | console.log('Available Pizzas in the Shop =>', pizzas); 64 | // Find if my pizza is availavle 65 | let myPizza = pizzas.find((pizza) => { 66 | return (pizza.type === type && pizza.name === name); 67 | }); 68 | if (myPizza) { 69 | console.log(`Yes, we found the customer pizza: ${myPizza.name}`); 70 | // Check for the free beverages 71 | console.log('Querying for the available beverages...'); 72 | query(`/api/pizzahub/beverages/${myPizza.id}`, function(result, error){ 73 | if (!error) { 74 | let beverage = result.beverage; 75 | console.log(`Beverage free with this order is, ${beverage}`); 76 | 77 | console.log(`Hold tight! Placing your order...`); 78 | // Prepare an order 79 | createOrder({'type': type, 'name': name, 'beverage': beverage}, function(result, error){ 80 | if (!error) { 81 | console.log(result); 82 | } else { 83 | console.log(`Bad luck, Try Again!`); 84 | } 85 | }); 86 | 87 | } else { 88 | error('Error Fetching the beverages'); 89 | } 90 | }) 91 | } else { 92 | console.warn(`Sorry, we don't have ${type} ${name} pizza. Do you want anything else?`); 93 | } 94 | } else { 95 | error('Error fetching the shop'); 96 | } 97 | }); 98 | } 99 | }); 100 | } 101 | 102 | // Call the orderPizza method 103 | orderPizza('nonveg', 'chicken cheese'); -------------------------------------------------------------------------------- /src/02-promise-chain/02-promise-chain-finally.js: -------------------------------------------------------------------------------- 1 | // Showing .finally() usage 2 | 3 | // Create a Promise 4 | let promise = new Promise(function (resolve, reject) { 5 | resolve("Testing Finally."); 6 | }); 7 | // Run .finally() before .then() 8 | promise 9 | .finally(function () { 10 | console.log("Running .finally()"); 11 | }) 12 | .then(function (value) { 13 | console.log(value); 14 | }); 15 | -------------------------------------------------------------------------------- /src/02-promise-chain/02-promise-chain-pizza.js: -------------------------------------------------------------------------------- 1 | const FETCH_SHOP_ID_DELAY = 1000; 2 | const FETCH_PIZZA_DETAILS_DELAY = 1500; 3 | const FETCH_BEVERAGES_DETAILS_DELAY = 1000; 4 | const CREATE_ORDER_DELAY = 2000; 5 | const DELIVER_ORDER_DELAY = 1000; 6 | 7 | const fetchNearByShop = ({lang, lat}) => { 8 | console.log(`🧭 Locating the nearby shop at (${lang} ${lat})`); 9 | return new Promise((resolve, reject) => { 10 | setTimeout(function () { 11 | // Let's assume, it is a nearest pizza shop 12 | // and resolve the promise using the shop id. 13 | const response = { 14 | shopId: "s-123", 15 | }; 16 | resolve(response.shopId); 17 | }, FETCH_SHOP_ID_DELAY); 18 | }); 19 | } 20 | 21 | const fetchAvailablePizzas = ({shopId}) => { 22 | console.log(`Getting Pizza List from the shop ${shopId}...`); 23 | return new Promise((resolve, reject) => { 24 | setTimeout(function () { 25 | const response = { 26 | // The list of pizzas 27 | // available at the shop 28 | pizzas: [ 29 | { 30 | type: "veg", 31 | name: "margherita", 32 | id: "pv-123", 33 | }, 34 | { 35 | type: "nonveg", 36 | name: "pepperoni slice", 37 | id: "pnv-124", 38 | }, 39 | ], 40 | }; 41 | resolve(response); 42 | }, FETCH_PIZZA_DETAILS_DELAY); 43 | }); 44 | } 45 | 46 | // Returns a promise with pizza that matches the customer request 47 | let getMyPizza = (result, type, name) => { 48 | let pizzas = result.pizzas; 49 | console.log("Got the Pizza List", pizzas); 50 | let myPizza = pizzas.find((pizza) => { 51 | return (pizza.type === type && pizza.name === name); 52 | }); 53 | return new Promise((resolve, reject) => { 54 | if (myPizza) { 55 | console.log(`✔️ Found the Customer Pizza ${myPizza.name}!`); 56 | resolve(myPizza); 57 | } else { 58 | reject( 59 | new Error( 60 | `❌ Sorry, we don't have ${type} ${name} pizza. Do you want anything else?` 61 | ) 62 | ); 63 | } 64 | }); 65 | }; 66 | 67 | const fetchBeverages = ({pizzaId}) => { 68 | console.log(`🧃 Getting Beverages for the pizza ${pizzaId}...`); 69 | return new Promise((resolve, reject) => { 70 | setTimeout(function () { 71 | const response = { 72 | id: "b-10", 73 | name: "cola", 74 | }; 75 | resolve(response); 76 | }, FETCH_BEVERAGES_DETAILS_DELAY); 77 | }); 78 | } 79 | 80 | function fetch(endpoint, payload) { 81 | if (endpoint.includes("/api/pizzahub/shop")) { 82 | return fetchNearByShop(payload); 83 | } else if (endpoint.includes("/api/pizzahub/pizza")) { 84 | return fetchAvailablePizzas(payload); 85 | } else if (endpoint.includes("/api/pizzahub/beverages")) { 86 | return fetchBeverages(payload); 87 | } 88 | } 89 | 90 | // Create the order 91 | let create = (endpoint, payload) => { 92 | if (endpoint.includes("/api/order")) { 93 | console.log("Placing the pizza order with...", payload); 94 | const { type, name, beverage } = payload; 95 | return new Promise((resolve, reject) => { 96 | setTimeout(function () { 97 | resolve({ 98 | success: true, 99 | message: `🍕 The ${type} ${name} pizza order with ${beverage} has been placed successfully.`, 100 | }); 101 | }, CREATE_ORDER_DELAY); 102 | }); 103 | } 104 | }; 105 | 106 | 107 | function orderPizza(type, name) { 108 | // Get the Nearby Pizza Shop 109 | fetch("/api/pizzahub/shop", {'lang': 38.8951 , 'lat': -77.0364}) 110 | // Get all pizzas from the shop 111 | .then((shopId) => fetch("/api/pizzahub/pizza", {'shopId': shopId})) 112 | // Check the availability of the selected pizza 113 | .then((allPizzas) => getMyPizza(allPizzas, type, name)) 114 | // Check the availability of the selected beverage 115 | .then((pizza) => fetch("/api/pizzahub/beverages", {'pizzaId': pizza.id})) 116 | // Create the order 117 | .then((beverage) => 118 | create("/api/order", { 119 | beverage: beverage.name, 120 | name: name, 121 | type: type, 122 | }) 123 | ) 124 | .then((result) => console.log(result.message)) 125 | .catch(function (error) { 126 | console.error(`${error.message}`); 127 | }); 128 | } 129 | 130 | // Order Pizza 131 | orderPizza("nonveg", "salami"); 132 | -------------------------------------------------------------------------------- /src/02-promise-chain/02-promise-chain-rethrow.js: -------------------------------------------------------------------------------- 1 | 2 | // Craete a promise 3 | var promise = new Promise(function(resolve, reject) { 4 | reject(401); 5 | }); 6 | 7 | // catch the error 8 | promise 9 | .catch(function(error) { 10 | if (error === 401) { 11 | console.log('Rethrowing the 401'); 12 | throw error; 13 | } else { 14 | // handle it here 15 | } 16 | }) 17 | .then(function(value) { 18 | // This one will not run 19 | console.log(value); 20 | }).catch(function(error) { 21 | // Rethrow will come here 22 | console.log(`handling ${error} here`); 23 | }); 24 | -------------------------------------------------------------------------------- /src/02-promise-chain/02-promise-chain-return-promise.js: -------------------------------------------------------------------------------- 1 | // Create a Promise 2 | let getUser = new Promise(function(resolve, reject) { 3 | const user = { 4 | name: 'John Doe', 5 | email: 'jdoe@email.com', 6 | password: 'jdoe.password' 7 | }; 8 | resolve(user); 9 | }); 10 | 11 | getUser 12 | .then(function(user) { 13 | console.log(`Got user ${user.name}`); 14 | // Return a Promise 15 | return new Promise(function(resolve, reject) { 16 | setTimeout(function() { 17 | // Fetch address of the user based on email 18 | resolve('Bangalore'); 19 | }, 1000); 20 | }); 21 | }) 22 | .then(function(address) { 23 | console.log(`User address is ${address}`); 24 | }); 25 | -------------------------------------------------------------------------------- /src/02-promise-chain/02-promise-chain-return-value.js: -------------------------------------------------------------------------------- 1 | // Return a value from the .then() handler 2 | 3 | // Create a Promise 4 | let getUser = new Promise(function (resolve, reject) { 5 | const user = { 6 | name: "John Doe", 7 | email: "jdoe@email.com", 8 | password: "jdoe.password", 9 | }; 10 | resolve(user); 11 | }); 12 | 13 | getUser 14 | .then(function (user) { 15 | console.log(`Got user ${user.name}`); 16 | // Return a simple value 17 | return user.email; 18 | }) 19 | .then(function (email) { 20 | console.log(`User email is ${email}`); 21 | }); 22 | -------------------------------------------------------------------------------- /src/02-promise-chain/02-promise-chain-throw-error.js: -------------------------------------------------------------------------------- 1 | let getUser = new Promise(function(resolve, reject) { 2 | const user = { 3 | name: 'John Doe', 4 | email: 'jdoe@email.com', 5 | permissions: [ 'db', 'hr', 'dev'] 6 | }; 7 | resolve(user); 8 | }); 9 | 10 | getUser 11 | .then(function(user) { 12 | console.log(`Got user ${user.name}`); 13 | // Let's reject if a dev is having the HR permission 14 | if(user.permissions.includes('hr')){ 15 | throw new Error('You are not allowed to access the HR module.'); 16 | } 17 | // else resolve as usual 18 | }) 19 | .then(function(email) { 20 | console.log(`User email is ${email}`); 21 | }) 22 | .catch(function(error) { 23 | console.error(error) 24 | }); 25 | -------------------------------------------------------------------------------- /src/02-promise-chain/02-promise-chain.js: -------------------------------------------------------------------------------- 1 | // Chaining Promises - Basic Usage 2 | 3 | // Create a Promise 4 | let promise = new Promise(function (resolve, reject) { 5 | resolve("Resolving a fake Promise."); 6 | }); 7 | 8 | // Create a Promise Chain 9 | promise 10 | .then(function (value) { 11 | console.log(value); 12 | return value; 13 | }) 14 | .then(function (value) { 15 | console.log(`${value} Second time.`); 16 | }); 17 | -------------------------------------------------------------------------------- /src/02-promise-chain/02-promise-handle-reject-catch.js: -------------------------------------------------------------------------------- 1 | // Handling the reject with the .catch() handler 2 | 3 | // Create a Promise 4 | let promise = new Promise(function (resolve, reject) { 5 | reject(new Error("Rejecting a fake Promise to handle with .catch().")); 6 | }); 7 | 8 | // Handle it using the .then() handler 9 | promise.catch(function (value) { 10 | console.error(value); 11 | }); 12 | -------------------------------------------------------------------------------- /src/02-promise-chain/02-promise-handle-reject-then.js: -------------------------------------------------------------------------------- 1 | // Handling the reject with the .then() handler 2 | 3 | // Create a Promise 4 | let promise = new Promise(function (resolve, reject) { 5 | reject(new Error("Rejecting a fake Promise to handle with .then().")); 6 | }); 7 | 8 | // Handle it using the .then() handler 9 | promise.then(null, function (value) { 10 | console.error(value); 11 | }); 12 | -------------------------------------------------------------------------------- /src/02-promise-chain/02-promise-not-a-chain.js: -------------------------------------------------------------------------------- 1 | // This is not Chaining Promises 2 | 3 | // Create a Promise 4 | let promise = new Promise(function (resolve, reject) { 5 | resolve(10); 6 | }); 7 | 8 | // Calling the .then() method multiple times 9 | // on a single promise - It's not a chain 10 | promise.then(function (value) { 11 | value++; 12 | // console.log(value); 13 | return value; 14 | }); 15 | 16 | promise.then(function (value) { 17 | value = value + 10; 18 | // console.log(value); 19 | return value; 20 | }); 21 | 22 | promise.then(function (value) { 23 | value = value + 20; 24 | console.log(value); 25 | return value; 26 | }); 27 | -------------------------------------------------------------------------------- /src/02-promise-chain/02-simple-promise-handling.js: -------------------------------------------------------------------------------- 1 | // Handling resolve with the .then() handler 2 | // Create a Promise 3 | let promise = new Promise(function(resolve, reject) { 4 | resolve('Resolving a fake Promise.'); 5 | }); 6 | 7 | // Handle it using the .then() handler 8 | promise.then(function(value) { 9 | console.log(value); 10 | }); 11 | -------------------------------------------------------------------------------- /src/03-async-await/03-async-await-basics.js: -------------------------------------------------------------------------------- 1 | 2 | const getTimeClock = () => { 3 | return new Date().getHours() 4 | + ":" 5 | + new Date().getMinutes() 6 | + ":" 7 | + new Date().getSeconds(); 8 | }; 9 | 10 | function getSynchronousHi() { 11 | return 'Hi'; 12 | } 13 | 14 | function getHelloFromAPromise() { 15 | return Promise.resolve('Hello'); 16 | } 17 | 18 | function getHolaWihthADelay() { 19 | return new Promise(function (resolve, reject) { 20 | setTimeout(function () { 21 | resolve('Hola'); 22 | }, 4000); 23 | }); 24 | } 25 | 26 | 27 | async function caller() { 28 | 29 | const messageHi = await getSynchronousHi(); 30 | console.log(getTimeClock(), messageHi); 31 | 32 | const messageHello = await getHelloFromAPromise(); 33 | console.log(getTimeClock(), messageHello); 34 | 35 | const messageHola = await getHolaWihthADelay(); 36 | console.log(getTimeClock(), messageHola); 37 | 38 | } 39 | 40 | caller(); 41 | 42 | 43 | -------------------------------------------------------------------------------- /src/03-async-await/03-async-await-error-handling.js: -------------------------------------------------------------------------------- 1 | const validateUser = ({userId, password}) => { 2 | return new Promise((resolve, reject) => { 3 | setTimeout(() => { 4 | if (userId && password) { 5 | resolve(`${userId} you have been authenticated successfully!!!`); 6 | } else { 7 | reject({message: 'userId or Password could be blank!'}); 8 | } 9 | 10 | }, 2000); 11 | }); 12 | } 13 | 14 | const app = async () => { 15 | const data = { 16 | userId: '', 17 | password: '' 18 | }; 19 | 20 | try { 21 | console.log('Initializing...'); 22 | const result = await validateUser(data); 23 | console.log(result); 24 | } catch (e) { 25 | console.error(e.message); 26 | } 27 | } 28 | 29 | app(); -------------------------------------------------------------------------------- /src/03-async-await/03-async-await-pizza-hub.js: -------------------------------------------------------------------------------- 1 | const FETCH_SHOP_ID_DELAY = 1000; 2 | const FETCH_PIZZA_DETAILS_DELAY = 1500; 3 | const FETCH_BEVERAGES_DETAILS_DELAY = 1000; 4 | const CREATE_ORDER_DELAY = 2000; 5 | const DELIVER_ORDER_DELAY = 1000; 6 | 7 | const fetchNearByShop = async ({lang, lat}) => { 8 | console.log(`🧭 Locating the nearby shop at (${lang} ${lat})`); 9 | return new Promise((resolve, reject) => { 10 | setTimeout(function () { 11 | // Let's assume, it is a nearest pizza shop 12 | // and resolve the promise using the shop id. 13 | const response = { 14 | shopId: "s-123", 15 | }; 16 | resolve(response.shopId); 17 | }, FETCH_SHOP_ID_DELAY); 18 | }); 19 | } 20 | 21 | const fetchAvailablePizzas = async ({shopId}) => { 22 | console.log(`Getting Pizza List from the shop ${shopId}...`); 23 | return new Promise((resolve, reject) => { 24 | setTimeout(function () { 25 | const response = { 26 | // The list of pizzas 27 | // available at the shop 28 | pizzas: [ 29 | { 30 | type: "veg", 31 | name: "margherita", 32 | id: "pv-123", 33 | }, 34 | { 35 | type: "nonveg", 36 | name: "pepperoni slice", 37 | id: "pnv-124", 38 | }, 39 | ], 40 | }; 41 | resolve(response); 42 | }, FETCH_PIZZA_DETAILS_DELAY); 43 | }); 44 | } 45 | 46 | // Returns a promise with pizza that matches the customer request 47 | let getMyPizza = async (result, type, name) => { 48 | let pizzas = result.pizzas; 49 | console.log("Got the Pizza List", pizzas); 50 | let myPizza = pizzas.find((pizza) => { 51 | return (pizza.type === type && pizza.name === name); 52 | }); 53 | return new Promise((resolve, reject) => { 54 | if (myPizza) { 55 | console.log(`✔️ Found the Customer Pizza ${myPizza.name}!`); 56 | resolve(myPizza); 57 | } else { 58 | reject( 59 | new Error( 60 | `❌ Sorry, we don't have ${type} ${name} pizza. Do you want anything else?` 61 | ) 62 | ); 63 | } 64 | }); 65 | }; 66 | 67 | const fetchBeverages = async ({pizzaId}) => { 68 | console.log(`🧃 Getting Beverages for the pizza ${pizzaId}...`); 69 | return new Promise((resolve, reject) => { 70 | setTimeout(function () { 71 | const response = { 72 | id: "b-10", 73 | name: "cola", 74 | }; 75 | resolve(response); 76 | }, FETCH_BEVERAGES_DETAILS_DELAY); 77 | }); 78 | } 79 | 80 | async function fetch(endpoint, payload) { 81 | if (endpoint.includes("/api/pizzahub/shop")) { 82 | return fetchNearByShop(payload); 83 | } else if (endpoint.includes("/api/pizzahub/pizza")) { 84 | return fetchAvailablePizzas(payload); 85 | } else if (endpoint.includes("/api/pizzahub/beverages")) { 86 | return fetchBeverages(payload); 87 | } 88 | } 89 | 90 | // Create the order 91 | let create = async (endpoint, payload) => { 92 | if (endpoint.includes("/api/order")) { 93 | console.log("Placing the pizza order with...", payload); 94 | const { type, name, beverage } = payload; 95 | return new Promise((resolve, reject) => { 96 | setTimeout(function () { 97 | resolve({ 98 | success: true, 99 | message: `🍕 The ${type} ${name} pizza order with ${beverage} has been placed successfully.`, 100 | }); 101 | }, CREATE_ORDER_DELAY); 102 | }); 103 | } 104 | }; 105 | 106 | 107 | async function orderPizza(type, name) { 108 | try{ 109 | // Get the Nearby Pizza Shop 110 | const shopId = await fetch("/api/pizzahub/shop", { 111 | 'lang': 38.8951 , 112 | 'lat': -77.0364}); 113 | // Get all pizzas from the shop 114 | const allPizzas = await fetch("/api/pizzahub/pizza", { 115 | 'shopId': shopId}); 116 | // Check the availability of the selected pizza 117 | const pizza = await getMyPizza(allPizzas, type, name); 118 | // Check the availability of the selected beverage 119 | const beverage = await fetch("/api/pizzahub/beverages", { 120 | 'pizzaId': pizza.id}); 121 | // Create the order 122 | const result = await create("/api/order", { 123 | beverage: beverage.name, 124 | name: name, 125 | type: type, 126 | }); 127 | console.log(result.message); 128 | } catch(error){ 129 | console.error(error.message); 130 | }; 131 | } 132 | 133 | // Order Pizza 134 | orderPizza("nonveg", "pepperoni slice"); 135 | -------------------------------------------------------------------------------- /src/04-promis-apis/04-promise-all-settles.js: -------------------------------------------------------------------------------- 1 | // It resolves with the value red after 1 second 2 | const red = new Promise((resolve, reject) => { 3 | setTimeout(() => { 4 | resolve('red'); 5 | }, 1000); 6 | }); 7 | 8 | // It resolves with the value green after 3 seconds 9 | const green = new Promise((resolve, reject) => { 10 | setTimeout(() => { 11 | resolve('green'); 12 | }, 3000); 13 | }); 14 | 15 | // It resolves with the value blue after 5 seconds 16 | const blue = new Promise((resolve, reject) => { 17 | setTimeout(() => { 18 | reject('blue'); 19 | }, 5000); 20 | }); 21 | 22 | 23 | const testAllSettled = async () => { 24 | const colors = await Promise.allSettled([red, green, blue]); 25 | console.log(colors); 26 | colors.forEach(color => { 27 | console.log(color); 28 | }); 29 | } 30 | 31 | testAllSettled(); 32 | 33 | -------------------------------------------------------------------------------- /src/04-promis-apis/04-promise-all.js: -------------------------------------------------------------------------------- 1 | // It resolves with the value red after 1 second 2 | const red = new Promise((resolve, reject) => { 3 | setTimeout(() => { 4 | resolve('red'); 5 | }, 1000); 6 | }); 7 | 8 | // It resolves with the value green after 3 seconds 9 | const green = new Promise((resolve, reject) => { 10 | setTimeout(() => { 11 | resolve('green'); 12 | }, 3000); 13 | }); 14 | 15 | // It resolves with the value blue after 5 seconds 16 | const blue = new Promise((resolve, reject) => { 17 | setTimeout(() => { 18 | resolve('blue'); 19 | }, 5000); 20 | }); 21 | 22 | 23 | const testAll = async () => { 24 | const colors = await Promise.all([red, green, blue]); 25 | console.log(colors); 26 | colors.forEach(color => { 27 | console.log(color); 28 | }); 29 | } 30 | 31 | testAll(); 32 | 33 | -------------------------------------------------------------------------------- /src/04-promis-apis/04-promise-any.js: -------------------------------------------------------------------------------- 1 | // It resolves with the value red after 1 second 2 | const red = new Promise((resolve, reject) => { 3 | setTimeout(() => { 4 | resolve('red'); 5 | }, 1000); 6 | }); 7 | 8 | // It resolves with the value green after 3 seconds 9 | const green = new Promise((resolve, reject) => { 10 | setTimeout(() => { 11 | resolve('green'); 12 | }, 3000); 13 | }); 14 | 15 | // It resolves with the value blue after 5 seconds 16 | const blue = new Promise((resolve, reject) => { 17 | setTimeout(() => { 18 | resolve('blue'); 19 | }, 5000); 20 | }); 21 | 22 | 23 | const testAny = async () => { 24 | try{ 25 | const color = await Promise.any([red, green, blue]); 26 | console.log(color); 27 | catch(err) { 28 | console.log(err); 29 | } 30 | } 31 | 32 | testAny(); 33 | 34 | -------------------------------------------------------------------------------- /src/04-promis-apis/04-promise-race.js: -------------------------------------------------------------------------------- 1 | // It resolves with the value red after 1 second 2 | const red = new Promise((resolve, reject) => { 3 | setTimeout(() => { 4 | resolve('red'); 5 | }, 1000); 6 | }); 7 | 8 | // It resolves with the value green after 3 seconds 9 | const green = new Promise((resolve, reject) => { 10 | setTimeout(() => { 11 | reject('green'); 12 | }, 3000); 13 | }); 14 | 15 | // It resolves with the value blue after 5 seconds 16 | const blue = new Promise((resolve, reject) => { 17 | setTimeout(() => { 18 | resolve('blue'); 19 | }, 5000); 20 | }); 21 | 22 | 23 | const testRace = async () => { 24 | const color = await Promise.race([red, green, blue]); 25 | console.log(color); 26 | } 27 | 28 | testRace(); 29 | 30 | -------------------------------------------------------------------------------- /src/04-promis-apis/04-promise-resolve.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | // It resolves with the value green after 3 seconds 4 | const green = new Promise((resolve, reject) => { 5 | setTimeout(() => { 6 | resolve('green'); 7 | }, 3000); 8 | }); 9 | 10 | const resolveOne = async () => { 11 | const result = await Promise.resolve(green); 12 | console.group(result); 13 | } 14 | 15 | resolveOne(); -------------------------------------------------------------------------------- /src/callback/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | 6 | 7 |