<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by sakshi sinha on Medium]]></title>
        <description><![CDATA[Stories by sakshi sinha on Medium]]></description>
        <link>https://medium.com/@sakshiryan3?source=rss-88b5fbfc5439------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PWG0lqjdOOU_4brT</url>
            <title>Stories by sakshi sinha on Medium</title>
            <link>https://medium.com/@sakshiryan3?source=rss-88b5fbfc5439------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 16:30:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sakshiryan3/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[MCP Architecture, Explained: How a Request Travels from User to Tool and Back]]></title>
            <link>https://sakshiryan3.medium.com/mcp-architecture-explained-how-a-request-travels-from-user-to-tool-and-back-c339d4603b84?source=rss-88b5fbfc5439------2</link>
            <guid isPermaLink="false">https://medium.com/p/c339d4603b84</guid>
            <dc:creator><![CDATA[sakshi sinha]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 11:59:56 GMT</pubDate>
            <atom:updated>2026-10-04T12:00:39.655Z</atom:updated>
            <content:encoded><![CDATA[<p>A language model on its own can only produce text. It cannot check your inventory, upload a product or read a file unless something connects it to those systems.</p><p>The Model Context Protocol (MCP) is the open standard for that connection. It gives every AI application one common way to talk to external tools, so a tool written once works with any application that speaks the protocol.</p><p>This article follows a single request through an MCP system, from the moment a user types a message to the moment the answer comes back. One example tool carries the whole story: uploadProduct().</p><p><strong>The three players</strong></p><p>An MCP system has three participants: a host, a client that lives inside the host, and a server that lives outside it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FJV1ShKdxG4sw3gfH5mQg.png" /></figure><p>Two points are easy to mix up.</p><p><strong>MCP is the protocol, not a program.</strong> It is the set of rules the client and server use to talk: JSON-RPC 2.0 messages, sent over standard input/output for a local server or over Streamable HTTP for a remote one. The <em>MCP server</em> is the specialised program that acts as the connector between the LLM and external services, databases or file systems.</p><p><strong>The LLM never talks to the server directly.</strong> The model only produces a request to use a tool. The host and its MCP client make the actual call, which keeps the host in control of what runs.</p><p><strong>The architecture at a glance</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HBQBpPbXtvFIxYMH1JHVLw.png" /></figure><p>Solid arrows carry the request down and dashed arrows carry the response back up. The highlighted band is the protocol itself: the only place where the host and the server meet.</p><p><strong>The request lifecycle, step by step</strong></p><p>One thing happens before the user types anything. The MCP client asks the server which tools it offers, using a tools/list request. The host hands that list to the LLM, so the model knows uploadProduct exists and what inputs it takes.</p><p>With that in place, a request moves through six steps.</p><ol><li><strong>The user sends a request to the host application.</strong> Say the user types: “Add Blue Running Shoes to the store at 2,499 rupees.” The host is the UI layer, and it orchestrates everything between the user, the LLM and the MCP client.</li><li><strong>The LLM decides it needs an external capability.</strong> The host passes the message to the LLM together with the tool list. The model cannot upload a product by writing text, and it sees that uploadProduct fits. Instead of a final answer, it returns a tool call: the tool’s name plus the arguments.</li><li><strong>The MCP client sends the call to the MCP server.</strong> The host picks up the tool call and hands it to the client connected to the right server. The client wraps it in a tools/call message and sends it using the Model Context Protocol.</li><li><strong>The server matches the call to a tool it exposes.</strong> The server exposes tools such as uploadProduct(), each with a name, a description and an input schema. It finds the tool by name and invokes its implementation with the arguments.</li><li><strong>The tool’s implementation runs the business logic.</strong> This is ordinary backend code: validation of the inputs, authentication, and REST API calls to external services. The LLM never sees this code or the credentials it uses.</li><li><strong>The response travels back.</strong> The server returns a structured result to the MCP client. The host adds it to the conversation, and the LLM turns it into natural language for the user: “Blue Running Shoes are now live in your store.”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*un1A11HJAOwyG95wNAyXcw.png" /></figure><p><strong>What actually travels on the wire</strong></p><p>Three small pieces of JSON carry the whole exchange: the tool’s definition, the call and the result. The examples below are illustrative; the product, price and ID are made up.</p><p><strong>The tool definition.</strong> This is what the server returns for tools/list, and it is all the LLM ever knows about the tool.</p><p>{<br> “name”: “uploadProduct”,<br> “title”: “Upload Product”,<br> “description”: “Add a new product to the store catalog”,<br> “inputSchema”: {<br> “type”: “object”,<br> “properties”: {<br> “name”: { “type”: “string” },<br> “price”: { “type”: “number” },<br> “currency”: { “type”: “string” }<br> },<br> “required”: [“name”, “price”]<br> }<br> }</p><p><strong>The call (step 3).</strong> The MCP client sends this to the server.</p><p>{<br> “jsonrpc”: “2.0”,<br> “id”: 3,<br> “method”: “tools/call”,<br> “params”: {<br> “name”: “uploadProduct”,<br> “arguments”: {<br> “name”: “Blue Running Shoes”,<br> “price”: 2499,<br> “currency”: “INR”<br> }<br> }<br> }</p><p><strong>The implementation (step 5).</strong> Inside the server, the tool is a plain function. This sketch is pseudo-code, not a specific SDK.</p><p>def upload_product(name, price, currency=”INR”):<br> # 1. Validation<br> if price &lt;= 0:<br> return error(“Price must be greater than zero”)<br> <br> # 2. Authentication<br> token = get_service_token()<br> <br> # 3. REST API call to the external service<br> response = http.post(<br> “https://api.example-store.com/products”,<br> headers={“Authorization”: f”Bearer {token}”},<br> json={“name”: name, “price”: price, “currency”: currency},<br> )<br> <br> return text(f”Product created. ID: {response[‘id’]}. Status: live.”)</p><p><strong>The result (step 6).</strong> The server answers with the same id, so the client can match it to the call.</p><p>{<br> “jsonrpc”: “2.0”,<br> “id”: 3,<br> “result”: {<br> “content”: [<br> { “type”: “text”, “text”: “Product created. ID: P-1042. Status: live.” }<br> ]<br> }<br> }</p><p>These messages are trimmed to the parts that matter here. In the current spec revision (2026–07–28), each request also carries a _meta block with the protocol version and the client’s capabilities.</p><p><strong>Why the design works</strong></p><p>Each layer in this architecture exists to keep one concern out of the others.</p><ul><li><strong>Build once, use anywhere.</strong> A server that exposes uploadProduct() works with any host that speaks MCP. Nobody writes a custom integration per AI app.</li><li><strong>Secrets stay on the server.</strong> The LLM sees a name, a description, a schema and a result. API keys, tokens and business rules never enter the model’s context.</li><li><strong>The host stays in control.</strong> Because the model only requests a call, the host can ask the user to approve it, log it or block it before anything runs.</li><li><strong>Tools can change without touching the host.</strong> The client discovers tools at runtime, so adding updateProduct() to the server needs no change in the application.</li></ul><p>Tools are one of three things a server can expose. The other two are resources, which are data the model can read, and prompts, which are reusable templates.</p><p><strong>In short</strong></p><p>The LLM decides what needs doing, the MCP client carries the request, and the MCP server does the work. The protocol between them is the only thing all three have to agree on, and that is what makes the pieces interchangeable.</p><p><strong>Sources</strong></p><ul><li><a href="https://modelcontextprotocol.io/docs/learn/architecture">MCP architecture overview</a>, modelcontextprotocol.io: participants, transports, tools/list and tools/call, spec revision 2026–07–28</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c339d4603b84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Engineering]]></title>
            <link>https://sakshiryan3.medium.com/prompt-engineering-1c5865d8fc11?source=rss-88b5fbfc5439------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c5865d8fc11</guid>
            <dc:creator><![CDATA[sakshi sinha]]></dc:creator>
            <pubDate>Sun, 20 Oct 2024 19:19:56 GMT</pubDate>
            <atom:updated>2024-10-20T19:19:56.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hlUQY87HrWV2lYo6" /></figure><p>Have you ever felt like you’re speaking a different language when interacting with AI? You’re not alone. Welcome to the world of <strong>Prompt Engineering</strong> — the art and science of communicating effectively with artificial intelligence. 🤖💬</p><p>In an era where AI is becoming increasingly integrated into our daily lives, mastering the skill of prompt engineering isn’t just a nice-to-have; it’s becoming <em>essential</em>. Whether you’re a developer, a business professional, or simply an AI enthusiast, understanding how to craft the perfect prompt can unlock a world of possibilities. From generating creative content to solving complex problems, the power lies in your words. But how do you harness this power? 🔑🚀</p><p>In this blog post, we’ll dive deep into the fascinating realm of prompt engineering. We’ll explore everything from the basics of understanding what prompt engineering is, to crafting effective prompts, and even peek into advanced techniques. Get ready to transform your AI interactions and unlock the full potential of these powerful tools!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S6nMvjgZrdCx_l1a.jpg" /></figure><h3>Understanding Prompt Engineering</h3><h3>A. Definition and importance</h3><p>Prompt engineering is the art and science of crafting effective instructions or queries to guide AI language models in generating desired outputs. It plays a crucial role in optimizing interactions with large language models (LLMs) like ChatGPT, ensuring more accurate, relevant, and useful responses.</p><p>The importance of prompt engineering cannot be overstated:</p><ul><li>Enhances AI performance</li><li>Improves user experience</li><li>Enables complex task completion</li><li>Reduces errors and biases</li></ul><h3>B. Key components of effective prompts</h3><p>Effective prompts consist of several essential elements:</p><ol><li>Clear instructions</li><li>Context provision</li><li>Specific details</li><li>Desired output format</li></ol><p>Component Description Example Instruction Clear action or task “Summarize the following text” Context Background information “This is an article about climate change” Details Specific requirements “Focus on the economic impacts” Format Desired output structure “Provide a bullet-point list”</p><h3>C. Role in AI and machine learning</h3><p>Prompt engineering serves as a critical bridge between human intent and AI capabilities. It enables:</p><ul><li>Fine-tuning AI models for specific tasks</li><li>Extracting relevant information from large datasets</li><li>Guiding AI in creative processes</li><li>Improving natural language understanding and generation</li></ul><p>As AI continues to advance, the role of prompt engineering in shaping human-AI interactions will only grow in significance, making it an essential skill for developers, researchers, and AI enthusiasts alike.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q2vwe_y1cR5i3eBY" /></figure><h3>Crafting Effective Prompts</h3><p>Now that we understand the basics of prompt engineering, let’s delve into the art of crafting effective prompts. This crucial skill can significantly enhance your interactions with AI language models and improve the quality of outputs.</p><h3>Clear and Specific Instructions</h3><p>When crafting prompts, clarity and specificity are paramount. Vague or ambiguous instructions can lead to unexpected or irrelevant responses. To ensure the AI understands your intent:</p><ul><li>Use precise language</li><li>Break down complex tasks into smaller, manageable steps</li><li>Specify any constraints or limitations</li></ul><h3>Contextual Information</h3><p>Providing relevant context helps the AI generate more accurate and tailored responses. Consider including:</p><ul><li>Background information</li><li>Relevant details about the task or topic</li><li>Any specific perspective or tone you want the AI to adopt</li></ul><h3>Desired Output Format</h3><p>Clearly define the format you expect for the AI’s response. This could include:</p><ul><li>Structure (e.g., bullet points, paragraphs, tables)</li><li>Length (e.g., word count, number of examples)</li><li>Style (e.g., formal, casual, technical)</li></ul><h3>Examples and Constraints</h3><p>Offering examples and setting constraints can guide the AI towards producing the desired output. Consider:</p><p>Strategy Purpose Example Examples Demonstrate expected output “Provide three examples of effective prompts, similar to: ‘Explain quantum computing in simple terms.’” Constraints Limit scope or focus “Generate a 100-word summary without using technical jargon.”</p><p>By mastering these elements of prompt crafting, you’ll be well-equipped to harness the full potential of AI language models. Next, we’ll explore advanced prompt techniques to further refine your skills.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w9srPEhy68MIlWFi" /></figure><h3>Advanced Prompt Techniques</h3><p>As we delve deeper into prompt engineering, let’s explore some advanced techniques that can significantly enhance AI model performance and output quality.</p><h3>Chain-of-Thought Prompting</h3><p>Chain-of-thought prompting encourages AI models to break down complex problems into smaller, more manageable steps. This technique mimics human reasoning and can lead to more accurate and explainable results.</p><h3>Few-Shot Learning</h3><p>Few-shot learning involves providing the AI with a small number of examples to guide its responses. This technique is particularly useful when dealing with new or specialized tasks.</p><h3>Zero-Shot Prompting</h3><p>Zero-shot prompting pushes the boundaries of AI capabilities by asking the model to perform tasks without any specific examples. This technique relies on the model’s general knowledge and ability to infer context.</p><h3>Prompt Templates</h3><p>Prompt templates are pre-designed structures that can be customized for various tasks. They provide consistency and efficiency in prompt creation.</p><h3>Iterative Refinement</h3><p>Iterative refinement involves a cyclical process of prompting, analyzing results, and refining the prompt based on the output. This technique helps optimize prompts for better performance.</p><p>Here’s a comparison of these techniques:</p><p>Technique Best Used For Complexity Example Use Case Chain-of-Thought Complex problem-solving High Mathematical reasoning Few-Shot Learning Specialized tasks Medium Custom classification Zero-Shot Prompting General knowledge tasks Low Open-ended questions Prompt Templates Repetitive tasks Low Customer service chatbots Iterative Refinement Optimizing existing prompts High Fine-tuning language models</p><p>By mastering these advanced prompt techniques, you can significantly improve your AI interactions and achieve more sophisticated results. Next, we’ll explore the practical applications of prompt engineering in various industries and scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v-Kt9POJNp1ISxUg" /></figure><h3>Applications of Prompt Engineering</h3><p>Prompt engineering has revolutionized various fields, expanding the capabilities of AI systems and enhancing human-machine interactions. Let’s explore some key applications:</p><h3>A. Natural Language Processing</h3><p>Prompt engineering has significantly improved natural language processing (NLP) tasks, enabling more accurate and context-aware interactions. Here are some notable applications:</p><ul><li>Text summarization</li><li>Language translation</li><li>Sentiment analysis</li><li>Question answering systems</li></ul><p>NLP Task Prompt Engineering Impact Summarization Improved conciseness and relevance Translation Enhanced context preservation Sentiment Analysis More nuanced emotional understanding Q&amp;A Systems Increased accuracy and coherence</p><h3>B. Image Generation</h3><p>In the realm of visual content creation, prompt engineering has unlocked new possibilities:</p><ul><li>Realistic image synthesis</li><li>Style transfer and artistic renditions</li><li>Image editing and manipulation</li></ul><h3>C. Code Completion</h3><p>Developers benefit from prompt engineering in code-related tasks:</p><ul><li>Autocomplete suggestions</li><li>Bug detection and fixing</li><li>Code documentation generation</li></ul><h3>D. Data Analysis</h3><p>Prompt engineering enhances data analysis processes by:</p><ul><li>Automating data cleaning and preprocessing</li><li>Generating insightful visualizations</li><li>Providing natural language interfaces for database queries</li></ul><p>As we’ve seen, prompt engineering applications span diverse domains, each leveraging the power of well-crafted prompts to achieve remarkable results. Next, we’ll examine the challenges that arise in this rapidly evolving field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KzSVupbbEZ5UE8Um.jpg" /></figure><h3>Challenges in Prompt Engineering</h3><p>As prompt engineering continues to evolve, several challenges have emerged that demand attention from researchers and practitioners alike. These challenges not only affect the quality of AI-generated responses but also raise important ethical and security concerns.</p><h3>Ambiguity and Misinterpretation</h3><p>One of the primary challenges in prompt engineering is dealing with ambiguity and misinterpretation. AI models may struggle to understand context or nuance, leading to responses that miss the mark or provide irrelevant information. This issue can be particularly problematic in the following scenarios:</p><ul><li>Complex queries with multiple layers of meaning</li><li>Prompts containing idiomatic expressions or cultural references</li><li>Questions requiring domain-specific knowledge</li></ul><p>To mitigate this challenge, prompt engineers must focus on clarity and specificity when crafting prompts. Here’s a comparison of ambiguous vs. clear prompts:</p><p>Ambiguous Prompt Clear Prompt “Tell me about apples” “Describe the nutritional benefits of eating apples, including specific vitamins and minerals they contain” “How does it work?” “Explain the step-by-step process of how a nuclear power plant generates electricity”</p><h3>Bias and Ethical Considerations</h3><p>Another significant challenge in prompt engineering is addressing bias and ethical considerations. AI models can inadvertently perpetuate or amplify biases present in their training data, leading to potentially harmful or discriminatory outputs. Key areas of concern include:</p><ul><li>Gender and racial bias in language generation</li><li>Reinforcement of stereotypes in content creation</li><li>Ethical dilemmas in decision-making scenarios</li></ul><p>To tackle this challenge, prompt engineers must:</p><ol><li>Regularly audit and test prompts for potential biases</li><li>Incorporate diverse perspectives in prompt design</li><li>Implement ethical guidelines and safeguards in AI systems</li></ol><h3>Prompt Injection Attacks</h3><p>As AI systems become more sophisticated, so do the methods to exploit them. Prompt injection attacks represent a growing security concern in prompt engineering. These attacks involve manipulating input prompts to bypass system constraints or extract sensitive information. Common types of prompt injection attacks include:</p><ul><li>Jailbreaking: Attempts to override AI system limitations</li><li>Data exfiltration: Extracting confidential information from the model</li><li>Malicious code injection: Inserting harmful instructions into prompts</li></ul><p>To counter these threats, prompt engineers must:</p><ul><li>Implement robust input validation and sanitization</li><li>Develop advanced prompt filtering techniques</li><li>Continuously update and patch AI systems against known vulnerabilities</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tL7xIdSi4AiHCELY" /></figure><h3>Future of Prompt Engineering</h3><p>As the field of artificial intelligence continues to evolve, prompt engineering is poised to play a crucial role in shaping the future of AI interactions. Let’s explore some exciting developments on the horizon.</p><h3>Integration with AI Development</h3><p>Prompt engineering is becoming increasingly intertwined with AI development processes. As language models grow more sophisticated, developers are incorporating prompt engineering techniques directly into their AI architectures. This integration allows for more nuanced and context-aware responses, enhancing the overall user experience.</p><p>Integration Aspect Benefits Model Fine-tuning Improved performance on specific tasks Prompt Libraries Reusable, optimized prompts for common scenarios Dynamic Prompting Real-time adjustment based on user interactions</p><h3>Automated Prompt Generation</h3><p>The future of prompt engineering lies in automation. AI systems are being developed to generate and optimize prompts autonomously, reducing the need for manual intervention. This advancement will streamline the process of creating effective prompts and allow for rapid iteration and improvement.</p><p>Key features of automated prompt generation:</p><ul><li>Machine learning algorithms to analyze prompt effectiveness</li><li>Natural language processing to refine prompt clarity</li><li>A/B testing capabilities for continuous optimization</li></ul><h3>Standardization and Best Practices</h3><p>As prompt engineering matures, we can expect to see the emergence of industry-wide standards and best practices. These guidelines will help ensure consistency and quality across different AI applications and platforms.</p><ol><li>Ethical considerations in prompt design</li><li>Cross-platform compatibility standards</li><li>Performance metrics for prompt effectiveness</li><li>Documentation and version control for prompts</li></ol><p>With these developments, prompt engineering is set to become an even more integral part of AI interaction design, shaping the way we communicate with artificial intelligence in the years to come.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3NcUNUGjYUmgT-Ef" /></figure><p>Prompt engineering has emerged as a critical skill in the age of advanced language models. By mastering the art of crafting effective prompts, users can unlock the full potential of AI systems, enhancing productivity and creativity across various domains. From understanding the basics to exploring advanced techniques, prompt engineering offers a powerful toolkit for optimizing AI interactions.</p><p>As we look to the future, prompt engineering will continue to evolve, addressing current challenges and opening up new possibilities. Whether you’re a developer, researcher, or enthusiast, honing your prompt engineering skills is an investment in the future of human-AI collaboration. Embrace this emerging field and stay curious about its developments — the potential for innovation is limitless.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c5865d8fc11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating Database Troubles: A Guide to Common Issues and Solutions]]></title>
            <link>https://sakshiryan3.medium.com/navigating-database-troubles-a-guide-to-common-issues-and-solutions-13ff94d0e2fb?source=rss-88b5fbfc5439------2</link>
            <guid isPermaLink="false">https://medium.com/p/13ff94d0e2fb</guid>
            <dc:creator><![CDATA[sakshi sinha]]></dc:creator>
            <pubDate>Sat, 21 Sep 2024 19:32:25 GMT</pubDate>
            <atom:updated>2024-09-21T19:32:25.485Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cuYx6Fn8uISwEyXd.jpg" /></figure><p>🚨 <em>Database troubles got you down?</em> You’re not alone. From frustrating connection issues to performance bottlenecks, database problems can bring your business to a screeching halt. But fear not, intrepid data wrangler! 💪</p><p>In today’s digital landscape, databases are the unsung heroes powering everything from e-commerce platforms to social media networks. When they hiccup, the ripple effects can be devastating. <strong>But here’s the good news:</strong> with the right knowledge and tools, you can transform from a frazzled firefighter to a database troubleshooting pro.</p><p>Ready to unlock the secrets of database mastery? In this comprehensive guide, we’ll dive deep into the most common database issues, equipping you with the skills to diagnose, resolve, and prevent problems like a seasoned expert. From connection woes to security vulnerabilities, we’ve got you covered. Let’s embark on this journey to database nirvana together! 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lfp75v2Mwrbyc1ym" /></figure><h3>Understanding Common Database Issues</h3><p>Database administrators and developers often encounter a variety of challenges when managing and maintaining database systems. Let’s explore some of the most common database issues that can impact performance, security, and data integrity.</p><h3>A. Connection Problems</h3><p>Connection problems are among the most frequent issues faced by database users. These can manifest in various ways, such as:</p><ul><li>Inability to establish a connection</li><li>Intermittent disconnections</li><li>Slow connection times</li></ul><p>Common causes of connection problems include:</p><ol><li>Network issues</li><li>Incorrect configuration settings</li><li>Firewall restrictions</li><li>Server overload</li></ol><p>To troubleshoot connection problems, consider the following steps:</p><ol><li>Verify network connectivity</li><li>Check database server status</li><li>Review configuration files</li><li>Examine firewall rules</li></ol><h3>B. Security Vulnerabilities</h3><p>Database security is crucial for protecting sensitive information. Common security vulnerabilities include:</p><ul><li>Weak authentication mechanisms</li><li>Unencrypted data transmission</li><li>SQL injection attacks</li><li>Excessive user privileges</li></ul><p>To address these vulnerabilities, implement the following best practices:</p><p>Best Practice Description Strong Authentication Use multi-factor authentication and complex passwords Encryption Encrypt data at rest and in transit Input Validation Implement thorough input validation to prevent SQL injection Principle of Least Privilege Grant users only the minimum necessary permissions</p><h3>C. Data Integrity Concerns</h3><p>Maintaining data integrity is essential for ensuring the accuracy and reliability of your database. Common data integrity issues include:</p><ul><li>Duplicate records</li><li>Inconsistent data across tables</li><li>Orphaned records</li><li>Data type mismatches</li></ul><p>To address these concerns:</p><ol><li>Implement proper constraints (e.g., primary keys, foreign keys)</li><li>Use transactions for complex operations</li><li>Regularly perform data audits and cleanup</li><li>Implement data validation rules at the application level</li></ol><h3>D. Performance Bottlenecks</h3><p>Database performance issues can significantly impact user experience and system efficiency. Common performance bottlenecks include:</p><ul><li>Slow query execution</li><li>High CPU or memory usage</li><li>Disk I/O limitations</li><li>Inefficient indexing</li></ul><p>To optimize database performance:</p><ol><li>Analyze and optimize slow-running queries</li><li>Implement appropriate indexing strategies</li><li>Configure proper hardware resources</li><li>Use caching mechanisms where appropriate</li></ol><p>By understanding these common database issues, you’ll be better equipped to diagnose and resolve problems quickly. In the next section, we’ll delve deeper into the process of diagnosing database troubles to pinpoint the root causes of these issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GW7BLos7nmEdYf0U" /></figure><h3>Diagnosing Database Troubles</h3><p>When it comes to maintaining a healthy database system, proper diagnosis is key. Let’s explore effective methods for identifying and understanding database issues.</p><h3>A. Troubleshooting Methodologies</h3><p>Effective troubleshooting starts with a structured approach. Here are some proven methodologies:</p><ol><li>Systematic Elimination</li><li>Root Cause Analysis</li><li>Divide and Conquer</li></ol><h3>B. Conducting Health Checks</h3><p>Regular health checks are crucial for early detection of potential issues. Consider the following aspects:</p><ul><li>Query performance</li><li>Resource utilization</li><li>Backup integrity</li><li>Index fragmentation</li></ul><h3>C. Analyzing Log Files</h3><p>Log files are treasure troves of information. Here’s what to look for:</p><ul><li>Error messages</li><li>Slow query logs</li><li>Transaction logs</li><li>System event logs</li></ul><h3>D. Using Monitoring Tools</h3><p>Leverage monitoring tools to gain real-time insights into your database’s performance:</p><p>Tool Type Purpose Examples Performance Monitors Track resource usage New Relic, Datadog Query Analyzers Identify slow queries SQL Server Profiler, pg_stat_statements Network Monitors Detect connectivity issues Wireshark, tcpdump</p><h3>E. Identifying Symptoms</h3><p>Recognizing common symptoms can lead to faster diagnosis:</p><ol><li>Slow query response times</li><li>Frequent timeouts or connection drops</li><li>Unexpected high CPU or memory usage</li><li>Disk space issues</li><li>Data inconsistencies</li></ol><p>By mastering these diagnostic techniques, you’ll be well-equipped to tackle database troubles head-on. Next, we’ll delve into specific strategies for resolving connection issues, a common pain point in database management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PCKOvTah6MV-ANlI" /></figure><h3>Resolving Connection Issues</h3><p>Now that we have identified common database issues and learned how to diagnose them, let’s focus on resolving connection problems. Database connection issues can be frustrating, but with the right approach, they can be solved efficiently.</p><h3>A. Driver and Client Software Updates</h3><p>Outdated drivers or client software are often the culprits behind connection issues. To address this:</p><ol><li>Check the current versions of your database drivers and client software</li><li>Visit the official website of your database provider for the latest updates</li><li>Download and install the most recent compatible versions</li><li>Restart your application and database server after the update</li></ol><p>Software Type Update Frequency Benefits Database Drivers Quarterly Improved compatibility, bug fixes Client Software Monthly Enhanced features, security patches</p><h3>B. Authentication Troubleshooting</h3><p>Authentication problems can prevent successful connections. Here’s how to troubleshoot:</p><ul><li>Verify username and password accuracy</li><li>Check user permissions and roles</li><li>Ensure the user account is not locked or disabled</li><li>Review authentication method settings (e.g., password, certificate, token)</li></ul><h3>C. Network Configuration Fixes</h3><p>Network misconfigurations can also lead to connection issues. Address these by:</p><ol><li>Confirming firewall settings allow database traffic</li><li>Verifying correct port numbers are open and not blocked</li><li>Checking DNS resolution for database hostnames</li><li>Ensuring proper VPN configuration if connecting remotely</li></ol><p>By systematically addressing these areas, you can resolve most database connection issues. Next, we’ll explore how to optimize database performance for smoother operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ltg7BNaKLwp5q2Un" /></figure><h3>Optimizing Database Performance</h3><p>Now that we’ve covered how to diagnose and resolve connection issues, let’s focus on optimizing your database performance. By implementing the following strategies, you can significantly enhance your database’s efficiency and responsiveness.</p><h3>A. Hardware Upgrades</h3><p>Upgrading your hardware can provide an immediate boost to database performance. Consider the following options:</p><ul><li>Solid-State Drives (SSDs): Replace traditional hard disk drives with SSDs for faster read/write operations.</li><li>RAM Expansion: Increase memory to allow for larger data caches and quicker query processing.</li><li>CPU Upgrades: More powerful processors can handle complex queries and concurrent operations more efficiently.</li></ul><h3>B. Caching Solutions</h3><p>Implementing effective caching strategies can dramatically reduce database load and improve response times:</p><ol><li>In-memory caching</li><li>Application-level caching</li><li>Database query caching</li></ol><p>Caching Type Description Best Use Case In-memory Stores frequently accessed data in RAM High-traffic websites Application-level Caches data at the application tier Distributed systems Database query Stores results of expensive queries Complex analytics</p><h3>C. Indexing Strategies</h3><p>Proper indexing is crucial for optimizing query performance:</p><ul><li>Create indexes on frequently queried columns</li><li>Use composite indexes for multi-column queries</li><li>Regularly review and update indexes based on query patterns</li></ul><h3>D. Query Optimization Techniques</h3><p>Refining your queries can lead to significant performance improvements:</p><ol><li>Use EXPLAIN to analyze query execution plans</li><li>Avoid using SELECT * and retrieve only necessary columns</li><li>Optimize JOIN operations by using appropriate join types</li><li>Utilize partitioning for large tables to improve query performance</li></ol><p>By implementing these optimization techniques, you’ll be well on your way to achieving peak database performance. Next, we’ll explore how to ensure data integrity, which is crucial for maintaining the reliability of your optimized database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TkWLGU6QjnWJwsWv" /></figure><h3>Ensuring Data Integrity</h3><p>Now that we’ve explored ways to optimize database performance, let’s delve into the critical aspect of ensuring data integrity. Maintaining the accuracy and consistency of your data is paramount for any database system.</p><h3>A. Handling Concurrent Transactions</h3><p>Concurrent transactions can pose a significant challenge to data integrity. To address this, implement:</p><ul><li>Transaction isolation levels</li><li>Proper locking mechanisms</li><li>Optimistic and pessimistic concurrency control</li></ul><p>Here’s a comparison of common concurrency control methods:</p><p>Method Pros Cons Optimistic High throughput Potential for conflicts Pessimistic Prevents conflicts Can lead to deadlocks MVCC Scalable Complex implementation</p><h3>B. Data Validation Practices</h3><p>Implement robust data validation practices to maintain data integrity:</p><ol><li>Input validation</li><li>Data type constraints</li><li>Business rule enforcement</li><li>Referential integrity checks</li></ol><h3>C. Regular Backups and Recovery</h3><p>Establish a comprehensive backup and recovery strategy:</p><ul><li>Implement full, differential, and incremental backups</li><li>Test recovery procedures regularly</li><li>Store backups in secure, offsite locations</li></ul><h3>D. Implementing Constraints</h3><p>Use database constraints to enforce data integrity rules:</p><ul><li>Primary key constraints</li><li>Foreign key constraints</li><li>Unique constraints</li><li>Check constraints</li></ul><p>By implementing these data integrity measures, you’ll significantly reduce the risk of data corruption and inconsistencies. Next, we’ll explore how to strengthen your database security to further protect your valuable data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a7ZP27HuXGWUpXsB" /></figure><h3>Strengthening Database Security</h3><p>Now that we’ve addressed data integrity, let’s focus on fortifying your database’s defenses. Strengthening database security is crucial to protect sensitive information and maintain the trust of your users.</p><h3>A. Patch Management</h3><p>Implementing a robust patch management strategy is essential for maintaining database security. Regular updates help protect against known vulnerabilities and potential exploits.</p><ul><li>Establish a patch schedule</li><li>Test patches in a staging environment before deployment</li><li>Automate patch installation when possible</li><li>Keep detailed records of applied patches</li></ul><h3>B. Regular Security Audits</h3><p>Conducting regular security audits helps identify potential vulnerabilities and ensures compliance with security standards.</p><p>Audit Type Frequency Focus Areas Internal Monthly Access logs, user permissions External Quarterly Penetration testing, vulnerability scanning Compliance Annually Regulatory requirements, industry standards</p><h3>C. Encryption Strategies</h3><p>Implementing strong encryption protects data both at rest and in transit.</p><ul><li>Use industry-standard encryption algorithms (e.g., AES-256)</li><li>Encrypt sensitive data fields</li><li>Implement SSL/TLS for data in transit</li><li>Regularly rotate encryption keys</li></ul><h3>D. Access Control Best Practices</h3><p>Proper access control is crucial for preventing unauthorized data access and maintaining the principle of least privilege.</p><ol><li>Implement strong password policies</li><li>Use multi-factor authentication (MFA) for sensitive operations</li><li>Regularly review and update user permissions</li><li>Implement role-based access control (RBAC)</li><li>Monitor and log all database access attempts</li></ol><p>By implementing these database security best practices, you’ll significantly reduce the risk of data breaches and unauthorized access. Next, we’ll explore preventive measures to maintain overall database health and avoid future issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MALIZwhge1OsHM8E" /></figure><h3>Preventive Measures for Database Health</h3><p>Now that we’ve covered various aspects of database troubleshooting and optimization, let’s focus on preventive measures to maintain your database’s health and avoid future issues.</p><h3>A. Staff Training and Skill Development</h3><p>Investing in your team’s knowledge is crucial for maintaining a healthy database environment. Consider the following:</p><ul><li>Regular training sessions on database management best practices</li><li>Workshops on new database technologies and trends</li><li>Certification programs for database administrators</li></ul><h3>B. Documentation and Change Management</h3><p>Proper documentation and change management processes are essential for maintaining database health:</p><p>Documentation Type Purpose Schema diagrams Visual representation of database structure Change logs Record of all modifications made to the database Troubleshooting guides Step-by-step instructions for common issues Backup and recovery procedures Detailed plans for data protection</p><h3>C. Capacity Planning</h3><p>Proactive capacity planning helps prevent performance issues and downtime:</p><ol><li>Monitor resource usage trends</li><li>Forecast future growth and requirements</li><li>Plan for hardware upgrades or cloud scaling</li><li>Test scalability under various load conditions</li></ol><h3>D. Routine Maintenance Tasks</h3><p>Implementing regular maintenance tasks is crucial for database health:</p><ul><li>Weekly backups and recovery tests</li><li>Monthly index optimization and statistics updates</li><li>Quarterly security audits and access reviews</li><li>Bi-annual hardware checks and firmware updates</li></ul><p>By implementing these preventive measures, you’ll significantly reduce the likelihood of encountering database issues and ensure optimal performance over time. Next, we’ll summarize the key takeaways from this guide to database troubleshooting and maintenance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HmlzTB9Dous4drx2" /></figure><p>Database management is a critical aspect of modern IT systems, and being prepared for common issues is essential. By understanding the typical problems, learning to diagnose troubles effectively, and knowing how to resolve connection issues, you can maintain a robust database environment. Optimizing performance, ensuring data integrity, and strengthening security are key components of a healthy database ecosystem.</p><p>Remember, prevention is always better than cure. Implementing regular maintenance routines, monitoring database health, and staying up-to-date with best practices will help you avoid many common pitfalls. By following the guidelines outlined in this post, you’ll be well-equipped to navigate database troubles and keep your systems running smoothly, ensuring reliable data management for your organization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13ff94d0e2fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous Javascript — Exploring the other side of JS.]]></title>
            <link>https://sakshiryan3.medium.com/asynchronous-javascript-exploring-the-other-side-of-js-2b769f735d2f?source=rss-88b5fbfc5439------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b769f735d2f</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[sakshi sinha]]></dc:creator>
            <pubDate>Fri, 21 May 2021 18:49:02 GMT</pubDate>
            <atom:updated>2021-05-21T18:49:02.048Z</atom:updated>
            <content:encoded><![CDATA[<h3>Asynchronous Javascript — Exploring the other side of JS.</h3><p><a href="https://medium.com/@cskavi34/asynchronous-javascript-the-other-face-of-js-f9c8d74b0fa5?source=post_page-----f9c8d74b0fa5--------------------------------">May 22, 2021·10 min read</a></p><p>Ifyou’re new to Javascript then you might have bombarded with so many new words such as single-threaded, Non-blocking script, concurrency, callbacks, callback-hell, promises, and async-await e.t.c especially when it comes to Asynchronous javascript ( also known as ajax) it is way more hectic. In that case, this article could be a lifesaver for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*XWWm6zujkZAl32xC.png" /></figure><blockquote><em>So by definition ‘Javascript is single-threaded, non-blocking, concurrent language’. Yeah, it does make sense in one way. Maybe or May not!!!</em></blockquote><p>Unlike other multi-threaded programming languages such as Java and Ruby, javascript is a single-threaded programming language which means that whatever the code you have written is going to be executed in a single thread. This single-threaded behavior of javascript gave rise to a few potential problems. Also, there is a positive side such as eliminating the race condition.</p><p>Single-threaded means there will be a single call stack, single heap memory, and a callback/task queue. These things are provided by a javascript runtime environment (such as V8 engine of chrome). Also, we have some extra add-ons provided by browser’s called web API’s such as XHR , DOM, BOM, setTimeout e.t.c . These web API’s are not a part of the javascript runtime environment. But they are written using javascript on top of C++ libraries. The whole environment of javascript is depicted in the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/0*o-lu91kQJhgiUcBe" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*WGqp_EuyqaOtEKOg.png" /></figure><p>Javascript runtime environment</p><p>We don’t need to care much about the heap memory as it is the place where memory is allocated. Let’s concentrate more on the call stack. A call stack is a mechanism that stores the information of active subroutines or subprograms. The following demonstration will give you a glimpse of how a call stack works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/0*xosLIGqJ1v29XOPj" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pn_H0a2g7jv9mBSv.png" /></figure><p>call stack demonstration</p><p>So when the left side code is executed first the main() function will be placed in the call stack. As in the code, we are first calling the loginUser() function it will be placed on top of main() function in the call stack. Now the loginUser() function is calling checkDetails() function so now it will be placed on top of the stack. Now when checkDetails() function is executed it will return some value and now checkDetails() is popped out of the stack. Now the loginUser() function is not returning any value but anyhow once the function is executed successfully it will be popped out of the stack and finally, the main() function will be popped out. This can also be seen when an error happens inside nested function.</p><pre>function f3() {<br>   throw new Error(&quot;Things gone wrong&quot;);<br>}function f2() {<br>   f3();<br>}function f1() {<br>   f2();<br>}<br>f1();</pre><p>Now if we execute this above code we can see the call stack when the error is thrown by the last function(f3). The Object.&lt;anonymous&gt; is the main function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/0*z3jAPHk4doI8z7kG" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UIt5a0m_AhLXGUcC.png" /></figure><p>Till now everything is going fine as things are synchronous. Now let’s trouble our selves a little bit.</p><p><strong>What is blocking?</strong></p><p>Well, there is no formal definition for blocking but in general term’s we can represent blocking as something that is quite slow. So why slow things are called blocking?? While code is being executed imagine we called a function that needs to perform some specific task. Now the next line of code will be executed only if the previous function is completed since without popping the above function we can’t go for the next function. Thus the slow part is blocking the next part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/0*gJc4TxpL1bQpN3CK" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*cMTzYiFv9LzKEhqc.gif" /></figure><p>This can be demonstrated better using a loop. As loops are quite slow compared to console.log() .😅</p><pre>function sreverReq() {for (i = 0; i &lt; 1000000000; i++) {}}console.log(&quot;The starting of the page&quot;);console.log(&quot;Waiting for the server response&quot;)sreverReq(); // I need to wait 😔console.log(&quot;The rest of the webpage&quot;);</pre><p>Now if we execute the above code it will first log the “The starting of the page” then it will log “Waiting for the server response”. Now it will wait for the serverReq() function to complete. Till then the last line won’t be logged. Don’t confuse with the fact that why we are running the loop 10 billion times. Here we are simply simulating a server. So whenever a page is being loaded the client needs to request some data such as user data from the server. So, in that case, it will take some time for the server to fetch that data from the database and then send it to the client. Meanwhile, the page (UI) should load without waiting for the response from the server, or else it would be a bad experience for the user. By definition, javascript is non-blocking so to achieve non-blocking we need concurrency. Javascript runtime can do one thing at a time. It can’t do ajax request while some other code is running. The browser is more than just a runtime. The browser web API’s are the place where the concurrency kicks in. Take a look at the following code</p><pre>function serverReq() {setTimeout(() =&gt; console.log(&quot;Server responded&quot;),10000);}console.log(&quot;Starting of page&quot;);serverReq();console.log(&quot;The rest of the page&quot;);</pre><p>If we run the above code. The output will be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/0*WLXo8eopcWjQrTIy" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/0*w-3vqKCS3lNdpNya.png" /></figure><p>So clearly you can see first it logged “Starting of page” and then instead of logging server response it went to next line and then logged “The rest of the page” and in the last, it logged “Server responded”. So how this magic happened? This is because of the web APIs that the browser provided. As I mentioned that setTimeout() is also a web API but not a part of javascript runtime.</p><p>Don’t feel like turning back. I will give a quick overview of what just happened in the background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/0*PeJVn4zSuZihjLVQ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1eHGeJwVZsKTXHPl.png" /></figure><p>So when the above code is executed first the <em>console.log(“Starting of page”); </em>is pushed onto the stack and then when it logged the statement it is popped out. Now <em>serverReq() </em>function is pushed onto to the stack. The function will call <em>setTimeout() </em>as <em>setTimeout() </em>is a part of webAPIs it will be moved to web API runtime and from there the web API runtime will take care of<em> setTimeout() </em>function. Therefore, the <em>serverReq()</em> function will be popped out of the call stack. Now the next statement <em>“The rest of the page” </em>will be logged. Now the stack is empty. So, how does the callback of the <em>setTimeout() </em>magically enter into the call stack? Once 10 seconds are completed the callback function is pushed into the task queue and whenever the call stack is empty it will push the callback function into the call stack. The event loop takes care of these things. event loop pushes the callback function in the task queue into the stack. It won’t push things randomly into the stack even though if it’s time or completed because you can’t push something into the stack randomly as call stack traces all the subroutines. With this, you could have got a clear idea of the <strong>event loop.</strong></p><p>The event loop is responsible for all the events that occur while executing a javascript program. The event loops continuously loop’s over the call stack, task queues, and job queue. In the ES6 version of the Javascript, the job queue came into existence when the <strong>promises </strong>are just introduced. So the callbacks of promises (micro-tasks) will go into job queue and callbacks from macro tasks will go into task queue. Now the event loops execute these callbacks based on their readiness and priority. So for instance, if we consider the following piece of code</p><pre>console.log(&quot;Start&quot;); // synchronous callsetTimeout(() =&gt; console.log(&quot;macrotask&quot;), 0); // async callPromise.resolve().then(() =&gt; console.log(&quot;microtask&quot;)); //aynsc callconsole.log(&quot;End&quot;); //  synchronous call</pre><p>First “Start” will be logged as it has the highest priority and it is from the call stack. Later the setTimeout will be moved into the task queue and in the next line, Promise will be moved into the job queue. And now “End” will be logged as it is synchronous and is from the call stack. Now before going to loop again, the event loop check’s for job queue and if the promise is resolved it will execute that task, and at last when a new loop is started the setTimeout call be executed. This is the reason why “microtask” got logged before the “macrotask” even though the setTimeout() function got called before the promise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/0*0BKHG3wcULtalsaH" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*gWYWYpRJNwRxbjR-.png" /></figure><p>Talking about a microtask, macro task, and event loop, we came across terms such as callbacks and promises. Before going into callbacks let’s take a look at the following piece of code</p><pre>console.log(&quot;Start&quot;);function foo() {setTimeout(() =&gt; { return &quot;Inside the function&quot; }, 1000);}const data = foo();console.log(data);console.log(&quot;End&quot;);</pre><p>Guess, the second line of output. If your guess is “Inside the function” then you did a blunder mistake. The function foo() is an asynchronous function also a macro task so it will be executed in the next event loop but before that, we have a synchronous line of code where we are trying to store the value returned by foo() inside the <em>data </em>variable. It doesn’t make any sense in all the ways. Then again there is another line of code where we are logging the <em>data</em> variable. So, guess what will be the output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/0*EaBAaKUgHJvc_43h" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*o23SgXft2OHdfLv7.png" /></figure><p>By the time the data got logged nothing returned from function foo(). Therefore undefined is logged.</p><p>So how to solve this problem? with the help of a callback. A callback is a function that will be supplied as a parameter to another function and once the parent function is executed then it will call the callback. The above piece of code can be rewritten as</p><pre>console.log(&quot;Start&quot;);function foo(cb) {setTimeout(_ =&gt; cb(&quot;Inside the function&quot;), 1000);}foo((data) =&gt; console.log(data))console.log(&quot;End&quot;);</pre><p>Here in the above code, we are passing a function as a callback to <em>foo(). </em>Once the setTimeout function completes it’s waiting time then it is calling the callback of the function <em>foo(). </em>Now guess the output, this time you are right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/0*LSSb2LlNq9_BnS4B" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*5K6GOdiwqVfsequ2.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/0*mIFfcqqJxTdZB6di" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*V80odw_5ogI6amT3.png" /></figure><p>output for above piece of code</p><p>Seem’s pretty good right! callbacks are like a boon for developers. Really?:\</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/0*nbve7Cl_tsws6BlT" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*YYFAiqeHyHD9SZGw.gif" /></figure><p>Callbacks are really a lifesaver when needed but extensive use of callbacks gives rise to a problem called callback hell. A callback hell prevails if there are so many nested callbacks inside a function.<br>Although callback hell is not a problem, callback hell worsens the readability of code and will become a strenuous task for the developer to debug the code. You can read more about callback hell <a href="http://callbackhell.com/">here</a>.</p><p>Let’s take a look how a callback hell look’s like</p><p>callback hell</p><p>The output for the above piece of code is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/0*FYiMO7Omd_LBpgFn" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-A0SiiO9fPZVeaut.png" /></figure><p>As you can see the above piece of code executed perfectly without any error. But you can see the callback hell. We just used 3 callbacks while calling loginUser() function and it already became callback hell. So one must use callbacks wisely.</p><p><strong>Promises</strong></p><p>Promises are a great breakthrough in asynchronous javascript. They are introduced in the ES6 version of javascript. A promise is an object that may produce a single value some time in the future. A promise can be returned synchronously from an asynchronous function. A promise has three states named</p><ul><li><strong>resolved: </strong>when the promise successfully resolved.</li><li><strong>rejected: </strong>when the promise got rejected due to certain reasons.</li><li><strong>pending:</strong> A promise is in the pending state if it’s neither resolved not rejected.</li></ul><p>A promise is <strong>settled</strong> if it’s not pending (it has been resolved or rejected). Sometimes people use <em>resolved</em> and <em>settled</em> to mean the same thing: <em>not pending</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/0*BMdYVV1ceKluCxpR" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*-5_ll9WqCkGGvFTv.gif" /></figure><p>To create a promise the syntax is</p><pre>const promise = new Promise((resolve, reject) =&gt; {})</pre><p>let’s take a look at how we can return promise synchronously from an asynchronous function.</p><p>The output of the above code will be user logged in. If there are multiple promises and if they are not interdependent we can resolve all the promises at a time. Take a look at the following piece of code</p><p>The output of the above code is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/0*1hsiUVb7NtE1DydV" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/0*r1wwxOkLnAD-IO-M.png" /></figure><p>In the above code, we can see that promise1 needs 5 seconds to resolve and the promise2 needs 10 seconds to resolve. But in the above code, both will be resolved within 10 seconds but not 15 seconds. Thus it reduces the time needed to resolve both the promises asynchronously.</p><p>The main advantage of promise is promise chaining. As we can see that when a promise is resolved then the code inside <em>then() </em>block will be executed and in the end, we can attach a catch block to the chain, Thereby making it to handle any error that occurred inside the whole chain. Similarly, we can attach multiple promises to the chain thereby making it a chain of promise. The following piece of code exhibits promise chaining</p><p>Thus promise chain unchained us from hectic callback hell.</p><p><strong>async and await</strong></p><p>async and await came into the picture in ES8 (2017) version javascript. async and await are backed by promises itself. Their special syntax to work with promises makes it more comfortable for the developers to write asynchronous code in a synchronous pattern. It’s also easy to understand. In order to use an async function, we need to use the keyword async before the function. we can only use await inside an async function. You can’t use await keyword outside an async function. let’s rewrite the above code but this time without using promise chaining but instead using async and await. To read more about async and await click <a href="https://javascript.info/async-await">here</a>.</p><p>That’s all for this blog. Thanks for the patience.</p><h3>Sakshi Sinha</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b769f735d2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>