Promise in JavaScript with example

Promise in JavaScript with example

April 24, 2021

What is a Promise in JavaScript?

A promise is an object and it used to handle asynchronous operations in javascript. A promise has three states:

  1. pending
  2. fulfilled
  3. rejected

The Promise object supports two properties: state and result. While a Promise object is “pending” (working), the result is undefined. When a Promise object is “fulfilled”, the result is a value. When a Promise object is “rejected”, the result is an error object.

Example:

const uno = ()=>{
    return "I am one";
};

// const dos = async ()=>{

//     setTimeout(()=>{
//         return "I am Two";
//     },3000);
    
// };


const dos = ()=> {

return new Promise((resolve, reject)=>{
    setTimeout(()=>{
        resolve("I am two");
    },3000);
});
    
};


const tres = ()=>{
    return "I am Three";
};

const callMe = async ()=>{
    let valOne = uno();
    console.log(valOne);

    let valTwo = await dos();
    console.log(valTwo);


    let valThree = tres();
    console.log(valThree);
}


callMe();
function doPromise() {
    return new Promise(function (resolve, reject) {
        setTimeout(() => {
            const error = true;
            if (!error) {
                console.log('Function: Your promise has been resolved.');
                resolve();
            }
            else {
                console.log('Function: Your promise has not been resolved.');
                reject('Sorry not fullfilled...');
            }
        }, 3000);
    });
}

doPromise().then(function () {

    console.log("SW: Thanks for resolving...");

}).catch((error) => {
    console.log("SW: very bad. Reson: " + error);
})

console.log(typeof doPromise());
function outputText(value) {
  alert(value);
}

let promise = new Promise(function(myResolve, myReject) {
  let x = 0;

// some code (try to change x to 5)

  if (x == 0) {
    myResolve("OK");
  } else {
    myReject("Error");
  }
});

promise.then(
  function(value) {outputText(value);},
  function(error) {outputText(error);}
);

Javascript async function

An async function is a function declared with the async keyword, and the await keyword is permitted within them. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

async function name([param[, param[, ...param]]]) {
   statements
}

 

Leave A Comment