Skip to main content

Asyncronous Functions

 async and await are features in JavaScript (and TypeScript) that work together to simplify asynchronous code and make it look more like synchronous code. Here's a clear explanation of each:

async Function

The async keyword is used to define asynchronous functions. An async function is a function that operates asynchronously via the event loop, allowing other code to run in parallel while waiting for the asynchronous operation to complete.

  • Syntax: An async function is declared using the async keyword before the function declaration.

    javascript
    async function fetchData() { // Async operations go here }
  • Return Value: Async functions always return a Promise. If a value is explicitly returned from within the function, the Promise will resolve with that value. If an exception is thrown, the Promise will be rejected with the thrown value.

  • Usage: Async functions are typically used when dealing with asynchronous operations such as fetching data from a server, reading files, or any operation that involves waiting for some external event to complete.

await Operator

The await keyword is used within async functions to pause execution and wait for a Promise to resolve. It can only be used inside async functions.

  • Syntax: await is placed before a Promise-based function call or any expression that returns a Promise.

    javascript
    async function fetchData() { let result = await fetch('https://api.example.com/data'); let data = await result.json(); return data; }
  • Behavior: When await is used, the async function pauses execution until the Promise is resolved or rejected. This allows the async function to wait for the asynchronous operation to complete without blocking the execution of other code.

  • Error Handling: To handle errors when using await, you can use try...catch blocks around the await statements. If the awaited Promise rejects, the error will be thrown, and you can catch it.

Example

Here's a simplified example demonstrating the use of async and await:

javascript
async function fetchData() { try { let response = await fetch('https://api.example.com/data'); if (!response.ok) { throw new Error('Failed to fetch data'); } let data = await response.json(); return data; } catch (error) { console.error('Error fetching data:', error); throw error; // Re-throw the error to propagate it } } // Using fetchData fetchData() .then(data => console.log('Data fetched:', data)) .catch(error => console.error('Fetch error:', error));

Summary

  • async: Defines asynchronous functions that return a Promise.
  • await: Pauses execution within async functions until Promises are resolved or rejected.
  • Together, async and await make asynchronous code more readable and easier to write, especially when dealing with multiple asynchronous operations or handling errors.

By using async and await, you can write cleaner and more maintainable asynchronous JavaScript code that behaves more predictably and synchronously at the surface level, even though it operates asynchronously under the hood.

Comments

Popular posts from this blog

Get OTP from email

/** * Retrieves an OTP from Gmail in a headless tab. * @param {Object} options - The options for the function. * @param {string} options.email - The Gmail email address. * @param {string} options.password - The Gmail password. * @returns {Promise<string | null>} The OTP retrieved from the email. */ export async function getOtpFromGmail ({ email , password , } : { email : string ; password : string ; }) : Promise < string | null > { const { chromium } = require ( "playwright" ); // Launch a headless browser context for Gmail login const browser = await chromium . launch ({ headless : true }); const context = await browser . newContext (); const page = await context . newPage (); await page . goto ( "https://mail.google.com" ); const emailInput = await page . waitForSelector ( "#identifierId" ); await emailInput . fill ( email ); const emailNextButton = await page . wa...

Playwright Solution

 There is a web site need to run with browser. and which has zero downtime and alert and notifications pop up too. Third party applications are involved in and need to fix bugs too.What is the solution and how to create a framework for this scenario : need to use playwright as well 1. Understand the Requirements and Challenges: Zero Downtime: Ensure tests do not interrupt the service. Alerts and Notifications: Handle unexpected pop-ups gracefully. Third-Party Integrations: Test interactions with third-party services. Bug Fixing: Implement a process to identify and log bugs efficiently. 2. Set Up the Playwright Framework: Installation: Ensure Playwright is installed and configured. bash Copy code npm install playwright 3. Structure the Test Framework: Test Suites: Organize tests into suites (e.g., smoke tests, regression tests, integration tests). Page Object Model (POM): Use POM to manage page elements and actions. Configuration: Set up configurations for different envir...

Challenges

 One of the challenging situations I faced was identifying the correct locators for elements in our Angular application. Despite using developer tools like Chrome DevTools, it was often difficult to pinpoint the exact locators due to the complexity of the application and the dynamic nature of Angular's rendering. To overcome this, I frequently had to review the application's code in Bitbucket to understand the structure and find reliable locators. This approach allowed me to write more robust and reliable tests. Additionally, I communicated with developers to gain insights and confirm my findings, which helped streamline the process." As our application grew, the number of test scripts also increased, making the scripts larger and more chaotic. This was especially true for our end-to-end tests using Playwright and TypeScript. The test scripts became hard to manage and maintain because they contained both the test logic and the test data, leading to a lot of redundancy and ...