CCCPaste

JavaScript.promises

/* Creating a Promise */
const myPromise = new Promise((resolve, reject) => {
    let success = true; // Change to false to test rejection
    setTimeout(() => {
        success ? resolve('Promise Resolved!') : reject('Promise Rejected!');
    }, 1000);
});

myPromise
.then(result => console.log(result))
.catch(error => console.error(error))
.finally(() => console.log('Promise Completed'));

/* Chaining Promises */
const asyncTask = value => new Promise(resolve => setTimeout(() => resolve(value * 2), 1000));

asyncTask(5)
.then(result => {
    console.log(result); // 10
    return asyncTask(result);
})
.then(result => console.log(result))
.catch(err => console.log(err));

/* Promise.all - Runs all promises in parallel, resolves when all succeed */
Promise.all([asyncTask(2), asyncTask(3), asyncTask(4)])
.then(results => console.log(results)) // [4, 6, 8]
.catch(err => console.error(err));

/* Promise.race - Resolves/rejects with the first completed promise */
Promise.race([asyncTask(2), asyncTask(3), asyncTask(4)])
.then(result => console.log(result)) // First resolved value
.catch(err => console.error(err));

/* Promise.allSettled - Returns all promise results (fulfilled or rejected) */
Promise.allSettled([asyncTask(2), Promise.reject('Error!'), asyncTask(4)])
.then(results => console.log(results)) // Array of {status, value/reason}

/* Promise.any - Resolves with first fulfilled promise (ignores rejections) */
Promise.any([Promise.reject('Error 1'), asyncTask(3), Promise.reject('Error 2')])
.then(result => console.log(result)) // First resolved value
.catch(err => console.error(err.errors)); // Only if all fail

// Async/Await Syntax
async function fetchData() {
    try {
        const result = await asyncTask(10);
        console.log(result); // 20
    } catch(err) {
        console.error(err)
    }
}
fetchData();