Skip to main content

Javscript async await,promise.all() interview questions

1. The async and await keywords in JavaScript are used to work with asynchronous operations in a more synchronous-like manner. Here's a simple example demonstrating the use of async and await:

// Asynchronous function that returns a promise

function fetchData() {

    return new Promise(resolve => {

        // Simulate an asynchronous operation (e.g., fetching data from an API)

        setTimeout(() => {

            const data = 'Async data received!';

            resolve(data);

        }, 2000); // Simulating a 2-second delay

    });

}


// Asynchronous function using async/await

async function fetchDataAsync() {

    try {

        // Using the await keyword to wait for the promise to resolve

        const result = await fetchData();

        console.log(result);

    } catch (error) {

        console.error('Error:', error);

    }

}

// Call the async function

fetchDataAsync();

 

In this example:


The fetchData function returns a Promise that resolves after a simulated 2-second delay. This function could represent an asynchronous operation, such as fetching data from an API.


The fetchDataAsync function is marked as async, allowing the use of the await keyword inside it. Inside the function, await is used to wait for the fetchData promise to resolve.


When the promise from fetchData resolves, the result is logged to the console. If there is an error (e.g., a rejected promise), it is caught in the catch block.


Finally, the fetchDataAsync function is called, initiating the asynchronous operation.


This example showcases how async and await simplify working with promises and asynchronous code, making it appear more like traditional synchronous code.


2. Promise.all()  javscript example


Promise.all() is a useful method in JavaScript for handling multiple promises concurrently. It takes an array of promises as input and returns a new promise that fulfills with an array of the resolved values when all the input promises have been resolved. If any of the input promises is rejected, the returned promise is immediately rejected with the reason of the first rejected promise.


Here's an example demonstrating the usage of Promise.all():


javascript

Copy code

// Simulated asynchronous functions returning promises

function fetchData1() {

    return new Promise(resolve => {

        setTimeout(() => {

            resolve('Data from fetchData1');

        }, 2000);

    });

}


function fetchData2() {

    return new Promise(resolve => {

        setTimeout(() => {

            resolve('Data from fetchData2');

        }, 1500);

    });

}


function fetchData3() {

    return new Promise((resolve, reject) => {

        setTimeout(() => {

            // Simulating an error

            reject('Error from fetchData3');

        }, 1000);

    });

}


// Using Promise.all() to handle multiple promises

async function fetchDataConcurrently() {

    try {

        const results = await Promise.all([fetchData1(), fetchData2(), fetchData3()]);


        // If all promises resolve, results will be an array of their resolved values

        console.log('All promises resolved:', results);

    } catch (error) {

        // If any promise is rejected, the error will be caught here

        console.error('Error:', error);

    }

}


// Call the function to initiate the concurrent fetching

fetchDataConcurrently();

In this example:


fetchData1, fetchData2, and fetchData3 are asynchronous functions that return promises.


The fetchDataConcurrently function uses Promise.all() to concurrently execute these promises.


The await keyword is used to wait for the completion of all promises passed to Promise.all().


If all promises resolve successfully, the results array will contain the resolved values from each promise.


If any of the promises is rejected, the error will be caught in the catch block.


This allows for efficient handling of multiple asynchronous operations, especially when you need to wait for all of them to complete before proceeding.

Comments

Popular posts from this blog

Interview questions related to Laravel 8 updates- Laravel Interview questions

 Laravel 8 brought several updates and features to the framework. If you are preparing for an interview and expecting questions related to Laravel 8 updates, here are some potential questions: 1. What are the major features introduced in Laravel 8? Laravel Jetstream: A new application scaffolding for Laravel, providing teams with a starting point for building robust applications. Laravel Breeze: A lightweight and minimalistic front-end starter kit. Model Factory Classes: Introduction of factory classes for model factories, allowing for better organization of data seeding logic. Job Batching: A feature that allows you to easily run a batch of jobs and then perform some action when all the jobs have completed. Dynamic Blade Components: The ability to render Blade components dynamically. 2. Explain the improvements made to the Laravel job queue in version 8. Laravel 8 introduced Job Batching, which allows you to group multiple jobs into a batch and perform actions upon the completion ...

Vue Top Interview Questions

 1. Can you explain the Vue Composition API and its benefits? The Vue Composition API is a feature introduced in Vue 3 that revolutionizes the way we write Vue components by allowing us to compose our component logic using functions. Instead of scattering our component logic across various options like data, methods, computed, and watch, the Composition API encourages us to organize our logic into smaller, reusable functions called composition functions. One of the primary features of the Composition API is the setup() function. This function replaces the traditional options like data, methods, and others. Inside the setup() function, we can define reactive state using ref() and reactive() functions, set up lifecycle hooks using functions like onMounted(), and create computed properties and watchers using computed() and watch() functions. One significant benefit of the Composition API is better organization and reusability of code. By breaking our component logic into smaller funct...