javascript is syncronous or aynchrnous an give me examples in ayncronous

javascript is default asynchronous

normally syncchronous means one by line execution -> it will stop till before lin execution

aynchrnous also line by line-> if line is aynchrnous -> it will not stop  if before line is aynchrnous-> it will continue to next line

when asyncrhonos line executed -> that wil stop present execution


Certainly! Here's an example of asynchronous code in JavaScript using the setTimeout function:

function:

javascript
console.log("First"); 
setTimeout(() => { console.log("Third"); }, 2000); 
console.log("Second");

IIn the above code, we have three console.log statements. The first and second console.log statements are executed synchronously, so they will be logged immediately. However, the third console.log statement is placed inside the setTimeout function, which schedules it to be executed asynchronously after a delay of 2 seconds.

When you run this code, the output will be:

sql
First 
Second 
Third (logged after 2 seconds)

As you can see, the third console.log statement is executed asynchronously after the delay, allowing the code execution to continue without waiting for it. This demonstrates the asynchronous nature of JavaScript.

\

function fetchData(callback) {
setTimeout(() => {
const data = "Async data";
callback(data);
}, 2000);
}

function processData(data) {
console.log("Processing data:", data);
}

fetchData(processData);
console.log("This log statement is executed synchronously.");


function fetchData(callback) {
function name with argument or call avk function name
setTimeout(() => {after certain time it calls inside function
const data = "Async data";loads into data variable
callback(data);it callling a funciton
}, 2000);
}
function processData(data) {i it calls with argument
console.log("Processing data:", data);it prints in console
}
fetchData(processData);
it callse fetchdata function with call back processdata function
console.log("This log statement is executed synchronously.");
on load this url-> it wil prints firts console log, then fetch executed


In the above code, the fetchData function simulates an asynchronous operation that fetches data after a delay of 2 seconds. It accepts a callback function processData as an argument and invokes it with the fetched data. The processData function processes the data.



promise in javascript

promise is a object -> it has resolve and reject -> if it is success it goes to resolve 

if reject -> it will calls catch

A Promise is an object in JavaScript that represents the eventual completion or failure of an asynchronous operation and its resulting value. It provides a way to handle asynchronous operations in a more organized and manageable manner.

A Promise has three states:

  1. Pending: The initial state. The Promise is still in progress, and the final value is not available yet.
  2. Fulfilled: The Promise has resolved successfully. The operation completed, and the Promise holds the resulting value.
  3. Rejected: The Promise encountered an error or failure during its execution.

Here's a basic example of creating and using a Promise:


 s

const myPromise = new Promise((resolve, reject) => {
  // Asynchronous operation
  setTimeout(() => {
    const randomNumber = Math.random();
    if (randomNumber > 0.5) {
      resolve(randomNumber);
    } else {
      reject("Error: Random number is too small");
    }
  }, 2000);
});

myPromise
  .then(result => {
    console.log("Promise fulfilled with result:", result);
  })
  .catch(error => {
    console.log("Promise rejected with error:", error);
  });

s


In the example above, we create a Promise using the new Promise() constructor. Inside the Promise, we perform an asynchronous operation using setTimeout to generate a random number. If the generated number is greater than 0.5, the Promise is resolved with the number; otherwise, it is rejected with an error message.

To handle the result of the Promise, we use the .then() method, which takes a callback function to execute when the Promise is fulfilled. If the Promise is rejected, we can handle the error using the .catch() method, which takes a callback function for error handling.

Promises allow you to chain multiple asynchronous operations together using .then() and handle errors with .catch(). They provide a more structured and readable way to handle asynchronous code compared to using callbacks directly.


new promise()
new promise(()=>{});
es6 (()=>{})
const myPromise = new Promise((resolve, reject) => {
object with arguments using resolve and reject
// Asynchronous operation
setTimeout(() => {
const randomNumber = Math.random();
if (randomNumber > 0.5) {if true resolve
resolve(randomNumber);
} else {if false reject
reject("Error: Random number is too small");
}
}, 2000);
});
myPromisecalling myprmise function
.then(result => {success calling resolve
console.log("Promise fulfilled with result:", result);
})
.catch(error => {error catch
console.log("Promise rejected with error:", error);
});



  1. Using Promises:
  2. In this example, the fetchData function returns a Promise that resolves with the fetched data. The processData function is passed as a callback to the then method, which executes it when the Promise is resolved. If an error occurs, it is caught using the catch method.
function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = "Async data";
      resolve(data);
    }, 2000);
  });
}

function processData(data) {
  console.log("Processing data:", data);
}

fetchData()
  .then(processData)
  .catch(error => {
    console.error("Error:", error);
  });

console.log("This log statement is executed synchronously.");


s


s

  1. Using async/await:
function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = "Async data";
      resolve(data);
    }, 2000);
  });
}

async function processData() {
  try {
    const data = await fetchData();
    console.log("Processing data:", data);
  } catch (error) {
    console.error("Error:", error);
  }
}

processData();
console.log("This log statement is executed synchronously.");

sIn this example, the fetchData function returns a Promise. The processData function is marked as async and uses the await keyword to wait for the Promise to resolve before continuing execution. Any errors are caught using a try/catch block.

In all three examples, the log statement outside the asynchronous code block is executed synchronously, demonstrating that JavaScript allows non-blocking execution of asynchronous operations.


function fetchData() {fetchdata function
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = "Async data";
resolve(data);success resolve goto resolve
}, 2000);
});
}
async function processData() {declaring as acyncronouse functiopn
try {
const data = await fetchData();in async wait till fetch data is execute
console.log("Processing data:", data);
} catch (error) {
console.error("Error:", error);
}
}
processData();invoke function
console.log("This log statement is executed synchronously.");

















No comments:

Post a Comment

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...