├── .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 | [![Stargazers repo roster for @atapas/promise-interview-ready](https://reporoster.com/stars/atapas/promise-interview-ready)](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 | Callback 8 | 9 | 10 | 11 | 12 |

All the output is in the browser's console

13 | 14 | 15 | -------------------------------------------------------------------------------- /src/callback/main.js: -------------------------------------------------------------------------------- 1 | console.log('Callback'); 2 | 3 | function foo(bar) { 4 | bar() 5 | } 6 | 7 | foo(function() { 8 | console.log('bar'); 9 | }) 10 | 11 | // Pizza Hub 12 | function orderPizza(type, name, callback) { 13 | console.log('Ordering pizza...'); 14 | setTimeout(function () { 15 | let msg = `Your ${type} ${name} Pizza is ready! The total bill is $13`; 16 | console.log(`On the Pizzahub server ${msg}`); 17 | callback(msg); 18 | }, 3000); 19 | } 20 | 21 | // Robin's Phone 22 | orderPizza('veg', 'cheese', function (msg) { 23 | console.log(`On Robin's phone ${msg}`); 24 | }); -------------------------------------------------------------------------------- /src/common-mistakes/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Common Mistakes in Using Promises 8 | 9 | 10 | 11 |

All the output is in the Browser's console

12 | 13 | -------------------------------------------------------------------------------- /src/common-mistakes/main.js: -------------------------------------------------------------------------------- 1 | console.log('Common mistakes in using Promises'); 2 | 3 | // ~~~~~~~~~~~~~~ 1. Promises and Loops ~~~~~~~~~~~~~~ 4 | 5 | const users = ['saviomartin', 'victoria-lo', 'max-programming', 'atapas']; 6 | 7 | const fetchData = user => { 8 | return fetch(`https://api.github.com/users/${user}`); 9 | } 10 | 11 | const loopFetches = () => { 12 | for (let i = 0; i < users.length; i++) { 13 | console.log(`*** Fetching details of ${users[i]} ***`); 14 | const response = fetchData(users[i]); 15 | response.then(response => { 16 | response.json().then(user => { 17 | console.log(`${user.name} is ${user.bio} has ${user.public_repos} public repos and ${user.followers} followers`); 18 | }); 19 | }); 20 | } 21 | } 22 | 23 | const loopAll = async () => { 24 | const responses = await Promise.all(users.map(user => fetchData(user))); 25 | const data = await Promise.all(responses.map(response => response.json())); 26 | console.log(data); 27 | data.map(user => { 28 | console.log(`*** Fetching details of ${user.name} ***`); 29 | console.log(`${user.name} is ${user.bio} has ${user.public_repos} public repos and ${user.followers} followers`) 30 | }); 31 | } 32 | 33 | const loopFetchesAsync = async () => { 34 | for (let i = 0; i < users.length; i++) { 35 | console.log(`=== Fetching details of ${users[i]} ===`); 36 | const response = await fetchData(users[i]); 37 | const user = await response.json(); 38 | console.log(`${user.name} is ${user.bio} has ${user.public_repos} public repos and ${user.followers} followers`); 39 | } 40 | } 41 | 42 | // loopFetches(); 43 | // loopAll(); 44 | // loopFetchesAsync(); 45 | 46 | // ~~~~~~~~~~~~~~ 2. Chain vs. No Chain ~~~~~~~~~~~~~~ 47 | const ten = new Promise((resolve, reject) => { 48 | resolve(10); 49 | }); 50 | 51 | const promiseNoChain = () => { 52 | ten.then((result) => { 53 | return result + 10; 54 | }); 55 | ten.then((result) => { 56 | return result * 10; 57 | }); 58 | ten.then((result) => { 59 | return result - 10; 60 | }); 61 | ten.then((result) => { 62 | console.log(`With No Chaining ${result}`); 63 | }); 64 | } 65 | 66 | const promiseChain = () => { 67 | 68 | ten 69 | .then((result) => { 70 | return result + 10; 71 | }) 72 | .then((result) => { 73 | return result * 10; 74 | }) 75 | .then((result) => { 76 | return result - 10; 77 | }) 78 | .then((result) => { 79 | console.log(`With Promise Chaining ${result}`); 80 | }); 81 | } 82 | 83 | // promiseChain(); 84 | // promiseNoChain(); 85 | 86 | // ~~~~~~~~~~~~~~ 3. Not Handling Errors ~~~~~~~~~~~~~~ 87 | const oddEven = (num) => { 88 | return new Promise((resolve, reject) => { 89 | if (num % 2 === 0) { 90 | resolve("Even"); 91 | } else { 92 | reject(new Error("Odd")); 93 | } 94 | }); 95 | }; 96 | 97 | oddEven(11).then((result) => { 98 | console.log(result); 99 | }).catch((err) => { 100 | console.log(err.message); 101 | }); 102 | 103 | // ~~~~~~~~~~~~~~ 4. Skipping Functions in .then() ~~~~~~~~~~~~~~ 104 | const hello = Promise.resolve("Hello"); 105 | hello.then('world').then(result => console.log(result)); 106 | 107 | // ~~~~~~~~~~~~~~ 5. Promise for Synchronous Values ~~~~~~~~~~~~~~ 108 | 109 | const cache = { 110 | 'tapas.email.com': { 111 | 'name': 'Tapas Adhikary', 112 | 'blog': 'GreenRoots Blog' 113 | } 114 | }; 115 | 116 | const getData = (email) => { 117 | return new Promise((resolve, reject) => { 118 | setTimeout(() => { 119 | const userFromCache = cache[email]; 120 | if(!userFromCache) { 121 | // Make the call to fetch user data 122 | // update cache 123 | console.log('Make the call and update cache'); 124 | } else { 125 | console.log(`User details ${JSON.stringify(userFromCache)}`); 126 | } 127 | }, 2000); 128 | }) 129 | }; 130 | 131 | const refactoredGetData = (email) => { 132 | const userFromCache = cache[email]; 133 | if(userFromCache) { 134 | console.log(`User details ${JSON.stringify(userFromCache)}`); 135 | } else { 136 | return new Promise((resolve, reject) => { 137 | setTimeout(() => { 138 | console.log('Make the call and update cache'); 139 | }, 2000); 140 | 141 | }); 142 | } 143 | }; 144 | 145 | getData('tapas.email.com'); 146 | refactoredGetData('tapas.email.com'); 147 | 148 | // ~~~~~~~~~~~~~~ 6. Using unnecessary try-catch with promises ~~~~~~~~~~~~~~ 149 | 150 | // Redundant try-catch 151 | new Promise((resolve, reject) => { 152 | try { 153 | const value = getValue(); 154 | // do something with value 155 | resolve(value); 156 | } catch (e) { 157 | reject(e); 158 | } 159 | }) 160 | .then(result => console.log(result)) 161 | .catch(error => console.log(error)); 162 | 163 | // Better 164 | new Promise((resolve, reject) => { 165 | const value = getValue(); 166 | // do something with value 167 | resolve(value); 168 | }) 169 | .then(result => console.log(result)) 170 | .catch(error => console.log(error)); 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | JavaScript Asyncs and Promises 8 | 9 | 10 | 11 | 12 |

All Output is in the Browser Console.

13 |

Please open the browser console(using the F12 key)

14 | 15 | Access PromiViz 16 | 17 | -------------------------------------------------------------------------------- /src/js-sync-async/async_1.js: -------------------------------------------------------------------------------- 1 | // Async => Not occuring at the same time 2 | 3 | // Fetch data from server 4 | // Want to execute something with a delay 5 | // Wany to execute something after an event 6 | 7 | // 1. Browser APIs / Web APIs 8 | // setTimeoutout, click, mouse over 9 | 10 | // 2. Promises / 11 | 12 | function printMe() { 13 | console.log('Print Me'); 14 | } 15 | 16 | function test() { 17 | console.log('test'); 18 | } 19 | 20 | setTimeout(printMe, 0); 21 | test(); 22 | 23 | -------------------------------------------------------------------------------- /src/js-sync-async/async_2.js: -------------------------------------------------------------------------------- 1 | function f1() { 2 | console.log('f1'); 3 | } 4 | 5 | function f2() { 6 | console.log('f2'); 7 | } 8 | 9 | 10 | function main() { 11 | console.log('main'); 12 | setTimeout(f1, 0); 13 | f2(); 14 | } 15 | 16 | main(); -------------------------------------------------------------------------------- /src/js-sync-async/async_3.js: -------------------------------------------------------------------------------- 1 | function f1() { 2 | console.log('f1'); 3 | } 4 | 5 | function f2() { 6 | console.log('f2'); 7 | } 8 | 9 | function main() { 10 | console.log('main'); 11 | setTimeout(f1, 0); 12 | 13 | new Promise(function(resolve, reject) { 14 | resolve('I am a promise'); 15 | }).then(resolve => console.log(resolve)); 16 | 17 | f2(); 18 | } 19 | 20 | main(); 21 | 22 | -------------------------------------------------------------------------------- /src/js-sync-async/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | JavaScript Sync vs Async 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/js-sync-async/index.js: -------------------------------------------------------------------------------- 1 | function f1() { 2 | // Some code 3 | } 4 | 5 | function f2() { 6 | f1(); 7 | } 8 | 9 | function f3() { 10 | f2(); 11 | } 12 | 13 | // Invoke the functions 14 | f3(); 15 | -------------------------------------------------------------------------------- /src/tasks/answers.md: -------------------------------------------------------------------------------- 1 | # Answers of the Quizzes 2 | 3 | ## 1. [What's the output of this code?](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/readme.md#1-whats-the-output-of-this-code) 4 | 5 | Answer: **Let's do it!, f1, f1, f1, f1, in settimeout** 6 | 7 | Explanation: 8 | - "Let's do it!" gets added to Execution stack & gets executed first 9 | - Then f1() functions are called which are added to Execution stack & are executed 10 | - And finally setTimeout() function is called which is a Browser API call added to & executed from Job Queue by callback function 11 | 12 | 13 | 14 | ## 2. [Which statements are `true`? Select multiple.](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/readme.md#2-which-statements-are-true-select-multiple) 15 | 16 | Answer: 17 | - [X] JavaScript is single-threaded 18 | - [X] By default, JavaScript is synchronous 19 | - [ ] Only promises make JavaScript asynchronous 20 | - [ ] All function callbacks are asynchronous 21 | 22 | ## 3. [What's the output of the code below?](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/readme.md#3-whats-the-output-of-the-code-below) 23 | 24 | Answer: **Let's do it!, f4, f1, f3, f2** 25 | 26 | Explanation: 27 | - "Let's do it!" is executed by Execution Stack 28 | - f1() calls browser API, so gets added to Callback Queue 29 | - f4() gets added to Execution Stack and is executed 30 | - Event loop finds a callback function f1() in callback queue & executes it 31 | - f2() calls browser API and gets added to Callback Queue. Similarly f3() is added to callback queue 32 | - Now there is nothing in Execution Stack, so event loop checks & finds f2() & f3() callback functions in callback queue 33 | - f3() goes back into the stack after timeout, and gets executed 34 | - f2() too goes back into the stack after timeout, and gets executed 35 | 36 | 37 | 38 | ## 4. [Which statement is `true`? Select Only one.](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/readme.md#4-which-statement-is-true-select-only-one) 39 | 40 | Answer: **The job queue gets higher priority than the callback queue.** 41 | 42 | Explanation: The Job Queue also known as micro task and has higher priority of execution than Callback queue in event loop 43 | 44 | 45 | 46 | ## 5. [Guess the output](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/readme.md#5-guess-the-output) 47 | 48 | Answer: **Cartoon, Jerry, should it be right after Tom, before Jerry?, tom** 49 | 50 | Explanation: 51 | - Cartoon() gets executed in the Execution Stack 52 | - tom() calls Browser API and is added to Callback Queue 53 | - "should it be right after Tom, before Jerry?" is a Promise and gets added to Job Queue 54 | - Then Jerry() gets executed in the Execution Stack 55 | - Then the event loop find tom() in callback queue and promise in job queue. Promise is moved to execution stack & executed first due to job queue having high priority 56 | - After promise, event loop finds tom() in callback queue, moves it to execution stack & executes it 57 | 58 | 59 | 60 | ## 6. [Guess the output](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/readme.md#6-guess-the-output) 61 | 62 | Answer: **Cartoon, Jerry, I am a Promise, right after tom and doggy! Really?, I am a Promise after Promise!, Doggy, Tom** 63 | 64 | Explanation: 65 | - cartoon() is called initially which executes "Cartoon" in execution stack first 66 | - Then tom() & doggy() call Browser API and are moved to Callback Queue 67 | - Now Promises are made and moved to Job Queue 68 | - Now jerry() is moved to & executed in Execution stack 69 | - The event loop now finds promises in Job Queue which has higher priority than Callback Queue, the promises are moved to execution stack and executed. 70 | - "I am a Promise, right after tom and doggy! Really?" and "I am a Promise after Promise!" are executed one after the other 71 | - Now the execution stack is empty and Job queue too is empty, event loop checks and finds tasks in callback queue 72 | - doggy() completes its timeout and is moved to execution stack and is executed 73 | - Now tom() completes its timeout and is moved to execution stack and is executed 74 | 75 | 76 | 77 | ## 7. [Guess the output](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/readme.md#7-guess-the-output) 78 | 79 | Answer: **f4, Boom, Sonic, Albert, f1, f3, f2** 80 | 81 | Explanation: 82 | - f4() is moved to execution stack & executed initially 83 | - f1() calls browser API, so it is moved to callback queue 84 | - Promise for Boom is made and is moved to job queue. Since, there is nothing in execution stack, job queue is prioritized and moved back to execution stack for execution 85 | - f2() calls browser API, so it is moved to callback queue 86 | - Another Promise for Sonic is made and moved to job queue. And as there is nothing in execution stack, job queue gets prioritized & promise is moved to execution stack and executed 87 | - f3() calls browser API, and is moved to callback queue 88 | - Another Promise for Albert is made, moved to job queue, gets prioritized, moved to execution stack, gets executed 89 | - Now there is nothing in execution stack, event loops finds f1() & f3() in callback queue 90 | - Both f1() and f3() have same timeout of 0 ms, but since queue is FIFO data structure, f1() being added first to the queue, gets moved to execution stack first 91 | - f1() gets executed, f3() follows f1() to execution stack and is executed 92 | - Now f2() completes its timeout and is moved for execution in execution stack 93 | 94 | 95 | 96 | ## 8. [Guess the output](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/readme.md#8-guess-the-output) 97 | 98 | Answer: **f4, Sonic, Albert, f1, f2, f3** 99 | 100 | Explanation: 101 | - f4() is moved to execution stack & executed initially 102 | - f1() calls browser API, so it is moved to callback queue 103 | - Promise for Sonic is made and moved to job queue. And as there is nothing in execution stack & it doesn't make any browser API calls, promise is moved to execution stack and executed 104 | - f3() calls browser API, and is moved to callback queue 105 | - Another Promise for Albert is made, moved to job queue, gets prioritized, moved to execution stack, gets executed 106 | - Now there is nothing in execution stack, event loops finds f1(), and f3() in callback queue 107 | - Both f1() and f3() have same timeout of 0 ms. Since queue is FIFO data structure, f1() being added first to the queue, gets moved to execution stack first 108 | - f1() gets executed and execute f2() as well, f3() follows f1() and d2() to execution stack and is executed 109 | - Since the execution stack is empty, there is nothing left to execute. 110 | 111 | -------------------------------------------------------------------------------- /src/tasks/readme.md: -------------------------------------------------------------------------------- 1 | # quizzes 2 | 3 | The best way to learn a concept is by practicing it. Here is a bunch of quizzes that will help you to practice the JavaScript Asynchronous programming concepts. I hope you find it helpful. 4 | 5 | In case of any doubts or clarifications, please reach out to me on [Twitter](https://twitter.com/tapasadhikary) over DM. 6 | 7 | > 🏗️ 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(⭐). 8 | 9 | ## LICENSE 10 | This project is licensed under [MIT LICENSE](https://github.com/atapas/promise-interview-ready/blob/main/LICENSE). 11 | 12 | ## CONTRIBUTIONS 13 | Any positive contributions are welcome. Please refer the [Contribution Guide](https://github.com/atapas/promise-interview-ready/blob/main/CONTRIBUTING.md). 14 | 15 | ## Answer Validations 16 | - Fork this repo 17 | - Copy the content of this md file to a new file, `_answer.md`. 18 | - Provide your answers and explanations. 19 | - If you want me to look into your answers, explanations to validate, please feel free Create a PR with your md file change. Alternatively, you can DM the file to me on [Twitter](https://twitter.com/tapasadhikary). 20 | - You can verify your answers with the [answers.md file](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/answers.md). 21 | 22 | ## QUIZZES 23 | Let's get started. 24 | 25 | ### 1. What's the output of this code? 26 | 27 | ```js 28 | function f1() { 29 | console.log('f1'); 30 | } 31 | 32 | console.log("Let's do it!"); 33 | 34 | setTimeout(function() {console.log('in settimeout');}, 0); 35 | 36 | f1(); 37 | f1(); 38 | f1(); 39 | f1(); 40 | ``` 41 | Options are, 42 | - Let's do it!, in settimeout, f1, f1, f1, f1 43 | - Let's do it!, f1, f1, f1, f1, in settimeout 44 | - Let's do it!, f1, , in settimeout, f1, f1, f1 45 | 46 | Answer: **[Click here for Answer](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/answers.md#1-whats-the-output-of-this-code)** 47 | 48 | ### 2. Which statements are `true`? Select multiple. 49 | - [ ] JavaScript is single-threaded 50 | - [ ] By default, JavaScript is synchronous 51 | - [ ] Only promises make JavaScript asynchronous 52 | - [ ] All function callbacks are asynchronous 53 | 54 | Answer: **[Click here for Answer](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/answers.md#2-which-statements-are-true-select-multiple)** 55 | 56 | ### 3. What's the output of the code below? 57 | 58 | ```js 59 | function f1() { 60 | console.log('f1'); 61 | } 62 | 63 | function f2() { 64 | console.log('f2'); 65 | } 66 | 67 | function f3() { 68 | console.log('f3'); 69 | } 70 | 71 | function f4() { 72 | console.log('f4'); 73 | } 74 | 75 | console.log("Let's do it!"); 76 | 77 | setTimeout(function() {f1();}, 0); 78 | 79 | f4(); 80 | 81 | setTimeout(function() {f2();}, 5000); 82 | 83 | setTimeout(function() {f3();}, 3000); 84 | ``` 85 | Options are, 86 | - Let's do it!, f4, f1, f3, f2 87 | - Let's do it!, f1, f3, f2, f4 88 | - Let's do it!, f1, f2, f3, f4 89 | - Let's do it!, f1, f4, f2, f3 90 | 91 | Answer: **[Click here for Answer](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/answers.md#3-whats-the-output-of-the-code-below)** 92 | 93 | 94 | ### 4. Which statement is `true`? Select Only one. 95 | - (_) JavaScript Function Execution Stack(Call Stack) never gets empty. 96 | - (_) The job queue gets higher priority than the callback queue. 97 | - (_) The only job of Event Loop is to manage the Call Stack 98 | - (_) The StackOverflow exception is random. 99 | 100 | Answer: **[Click here for Answer](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/answers.md#4-which-statement-is-true-select-only-one)** 101 | 102 | ### 5. Guess the output 103 | 104 | ```js 105 | const tom = () => console.log('Tom'); 106 | 107 | const jerry = () => console.log('Jerry'); 108 | 109 | const cartoon = () => { 110 | console.log('Cartoon'); 111 | 112 | setTimeout(tom, 5000); 113 | 114 | new Promise((resolve, reject) => 115 | resolve('should it be right after Tom, before Jerry?') 116 | ).then(resolve => console.log(resolve)) 117 | 118 | jerry(); 119 | } 120 | 121 | cartoon(); 122 | ``` 123 | Options are, 124 | - Cartoon, Jerry, should it be right after Tom, before Jerry?, tom 125 | - Cartoon, Tom, Jerry, should it be right after Tom, before Jerry?, 126 | - Cartoon, Tom, should it be right after Tom, before Jerry?, Jerry 127 | - Error 128 | 129 | Answer: **[Click here for Answer](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/answers.md#5-guess-the-output)** 130 | 131 | ### 6. Guess the output 132 | 133 | ```js 134 | const tom = () => console.log('Tom'); 135 | const jerry = () => console.log('Jerry'); 136 | const doggy = () => console.log('Doggy'); 137 | 138 | const cartoon = () => { 139 | console.log('Cartoon'); 140 | 141 | setTimeout(tom, 50); 142 | setTimeout(doggy, 30); 143 | 144 | new Promise((resolve, reject) => 145 | resolve('I am a Promise, right after tom and doggy! Really?') 146 | ).then(resolve => console.log(resolve)); 147 | new Promise((resolve, reject) => 148 | resolve('I am a Promise after Promise!') 149 | ).then(resolve => console.log(resolve)); 150 | 151 | jerry(); 152 | } 153 | 154 | cartoon(); 155 | ``` 156 | Options are, 157 | - Cartoon, Jerry, I am a Promise, right after tom and doggy! Really?, I am a Promise after Promise!, , Tom, Doggy 158 | - Cartoon, Jerry, I am a Promise after Promise!, I am a Promise, right after tom and doggy! Really?, Doggy, Tom 159 | - Cartoon, Jerry, I am a Promise, right after tom and doggy! Really?, I am a Promise after Promise!, Doggy, Tom 160 | - Cartoon, Tom, Doggy, I am a Promise, right after tom and doggy! Really?, I am a Promise after Promise!, Jerry 161 | - None of the above. 162 | 163 | Answer: **[Click here for Answer](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/answers.md#6-guess-the-output)** 164 | 165 | 166 | ### 7. Guess the output 167 | 168 | ```js 169 | const f1 = () => console.log('f1'); 170 | const f2 = () => console.log('f2'); 171 | const f3 = () => console.log('f3'); 172 | const f4 = () => console.log('f4'); 173 | 174 | f4(); 175 | 176 | setTimeout(f1, 0); 177 | 178 | new Promise((resolve, reject) => { 179 | resolve('Boom'); 180 | }).then(result => console.log(result)); 181 | 182 | setTimeout(f2, 2000); 183 | 184 | new Promise((resolve, reject) => { 185 | resolve('Sonic'); 186 | }).then(result => console.log(result)); 187 | 188 | setTimeout(f3, 0); 189 | 190 | new Promise((resolve, reject) => { 191 | resolve('Albert'); 192 | }).then(result => console.log(result)); 193 | ``` 194 | Options are, 195 | - f4, Boom, Sonic, Albert, f1, f3, f2 196 | - f4, f1, Boom, f2, Sonic, f3, Albert 197 | - f4, Boom, Sonic, Albert, f3, f1, f2 198 | - f4, Boom, Sonic, Albert, f1, f2, f3 199 | 200 | Answer: **[Click here for Answer](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/answers.md#7-guess-the-output)** 201 | 202 | 203 | ### 8. Guess the output 204 | 205 | ```js 206 | const f1 = () => { 207 | console.log('f1'); 208 | f2(); 209 | } 210 | const f2 = () => console.log('f2'); 211 | const f3 = () => console.log('f3'); 212 | const f4 = () => console.log('f4'); 213 | 214 | f4(); 215 | 216 | setTimeout(f1, 0); 217 | 218 | new Promise((resolve, reject) => { 219 | resolve('Sonic'); 220 | }).then(result => console.log(result)); 221 | 222 | setTimeout(f3, 0); 223 | 224 | new Promise((resolve, reject) => { 225 | resolve('Albert'); 226 | }).then(result => console.log(result)); 227 | ``` 228 | Options are, 229 | - f4, f1, f2, Sonic, f3, Albert 230 | - f4, Sonic, Albert, f3, f1, f2 231 | - f4, Sonic, Albert, f1, f2, f3 232 | - f4, Albert, Sonic, f1, f2, f3 233 | 234 | Answer: **[Click here for Answer](https://github.com/atapas/promise-interview-ready/blob/main/src/tasks/answers.md#8-guess-the-output)** 235 | 236 | --------------------------------------------------------------------------------