Izac Wiki

Asynchronous JS

Promises

In JavaScript, promises are used to handle asynchronous operations. Promises represent the eventual completion (or failure) of an asynchronous operation and allow you to write asynchronous code in a more synchronous manner. Here's an example:

      
        
function fetchData() {
return new Promise((resolve, reject) => {
// Asynchronous operation
// If operation is successful, call resolve() with the result
// If operation fails, call reject() with the error
});
}
fetchData().then(result => {
// Handle successful result
}).catch(error => {
// Handle error
});

In the above example, the function fetchData returns a new Promise that represents an asynchronous operation. The operation can either succeed (in which case resolve is called with the result) or fail (in which case reject is called with the error).

You can chain then() and catch() methods on a promise to handle the successful result or the error, respectively. This allows you to write code that executes in a specific order even though the underlying operations are asynchronous.

Async/Await

Async/await is a syntactic sugar for promises. It allows you to write asynchronous code in a more synchronous manner. Here's an example:

      
        
async function fetchData() {
const result = await someAsyncOperation();
return result;
}
try {
const result = await fetchData();
// Handle successful result
} catch (error) {
// Handle error
}

In the above example, the function fetchData is an asynchronous function that uses the await keyword to wait for the result of the someAsyncOperation function. The someAsyncOperation function represents an asynchronous operation that returns a promise.

If the operation is successful, the result is returned by the fetchData function. If the operation fails, an error is thrown and can be caught using a try-catch block.

By using async/await, you can write code that appears to execute synchronously, even though the underlying operations are asynchronous.