Skip to content

Zubair-hussain/Promise-Task

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 

Repository files navigation

πŸ’‘ JavaScript Promises β€” Complete Example & Guide

This project demonstrates several examples of how to use Promises in JavaScript.
Promises help manage asynchronous operations, replacing nested callbacks with a cleaner and more readable approach.


πŸ“˜ What is a Promise?

A Promise in JavaScript is an object that represents the eventual result of an asynchronous operation.

πŸ” Promise States:

  • 🟑 Pending β€” Initial state
  • βœ… Fulfilled β€” Operation completed successfully
  • ❌ Rejected β€” Operation failed

βœ… Example 1: Basic Resolved Promise

πŸ“œ Code:

const OnePromise = new Promise((resolve, reject) => {
    setTimeout(function () {
        console.log('Async Task is Complete');
        resolve();
    }, 1000);
});

OnePromise.then(function () {
    console.log("Promise Consumed");
});`


###  Terimale Answer:

``` Output:

Async Task is Complete
Promise Consumed

Example 2: Rejected Promise (Forced Rejection)

JavaScript Code:

const promiseSecond = new Promise((resolve, reject) => {
    setTimeout(function () {
        let error = false;

        if (error) {
            console.log("This is how a rejected promise works");
            reject("An error occurred");
        } else {
            console.log("This Promise has been used");
            reject("Forced rejection for demo");
        }
    }, 1000);
});

promiseSecond.catch(function () {
    console.log("This promise was used correctly after rejection");
});

Terminal Output:


This Promise has been used
This promise was used correctly after rejection

Example 3: Resolving with Data (User Object)

const ThirdPromise = new Promise((resolve, reject) => {
    setTimeout(function () {
        console.log("Default");
        resolve({ username: 'name', email: 'zubair@example.com' });
    }, 1000);
});

ThirdPromise.then(function (data) {
    console.log(data.username);
});

Ternimal Output:

Default
name

Example 4: Using async/await:

const Await = new Promise((resolve, reject) => {
    setTimeout(function () {
        console.log("processing");
        resolve("Done");
    }, 1000);
});

async function ConsumeAwait() {
    const response = await Await;
    console.log(response);
}

ConsumeAwait();

Ternimal Output:

processing
Done

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published