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

Mock server

 Using a mock server in end-to-end (E2E) testing is indeed common, and it can be used for more than just reading values. Mock servers simulate the behavior of real servers and can handle various HTTP methods, including POST , PUT , DELETE , and PATCH , in addition to GET . This means you can use a mock server to simulate interactions that involve writing data, such as filling out and submitting forms. Automating Form Interactions with Mock Servers Simulating Form Submissions : Mock servers can be set up to handle form submissions. When you submit a form in your E2E test, the mock server can capture the request and respond with a predefined response. Validating Data : You can use the mock server to validate the data sent by your application. The mock server can check if the request body matches the expected format and values. Response Handling : After submitting a form, your application typically processes the server's response. The mock server can provide specific responses to test...

Browser Context

 In the context of Playwright, understanding how pages and browser contexts work is crucial for managing test isolation and ensuring reliable test execution. Here’s an explanation: Browser Context in Playwright Definition : A browser context in Playwright is akin to a new browser profile. Each browser context provides a separate environment where cookies, local storage, and other session data are isolated from other contexts. Isolation Between Tests : When you run tests using Playwright, each test typically operates within its own browser context. This means that: Fresh Environment : Every test starts with a clean slate, ensuring that any changes made by one test (such as cookies or session data) do not affect subsequent tests. Consistent State : Tests are independent of each other in terms of state, which helps in avoiding interference between different test cases. Page Isolation : Within each browser context, individual pages (created using page objects in Playwright) are also i...