Promises in javascript

console.log("Anubhav and javascript");

function passwordchecker(Password){

let prom=new Promise((resolve,reject)=>{

if(Password.length>8)

{

resolve("yes it is more")

} else { reject(" not applicable") }

});

prom.then((result) =>

{

console.log(result);

// Output: Password meets the length requirement!

})

.catch((error) =>

{

console.error(error);

// Output: Password is too short. It must be at least 8 characters long.

});

}

passwordchecker("Anubhavaanand");

Promises:

Promises are the programme that does not execute at the same time ,they produce value only when the asynchronous function get executed .They are browser optimal codes which is processed by browser internally.

Promises have 2 callback function

1.Resolve

2.Reject

Resolve is called when the promise executed successfully. From its pending state the Promise moves to the fulfilled state when it got resolved.

Reject is a state when it didn't get executed.

Settled is a state of a promise in which it either get resolved or get rejected.

Result is nothing but resolved statement or value which is generated after execution of promise

This programme is written to add a authentication of password length i.e it should be greater than 8 .Firstly we have create a function that is accepting the password and then we have created a promise named pro.Now in if condition when the password length is more than 8 then it get resolved.

To access the promise

PromiseName

.then((result)=>{

// whatever we want to publish or get

} , //seperated by comma

(error)=>{

// when promise is rejected

}

.then functionality get attached to the promise we have made only when the resolve method is called in it. And we can pass the data from resolve also

like

resolve(username:"anubhav", roll_no:10)

promise syntax 1:

const promiseOne= new Promise(function(resolve,reject){

setTimeout(()=>{

console.log("chal ja bhi tu ab"),2000}

resolve()

)}

promiseOne.then(function(){

console.log("promise resolved")

}

Promise syntax 2:

new Promise(function(resolve,reject){

setTimeout(()=>{

console.log("chal ja bhi tu ab"),2000}

resolve()

)}.then(function(){

console.log("promise resolved")

}

Promise syntax 3:

new Promise(function(resolve,reject){

setTimeout(()=>{

console.log("chal ja bhi tu ab"),2000}

resolve(username:"anubhav", roll_no:10)

)}.then(( user )=>{

console.log(user)

return user.username // it will be passed to another .then as a data

}.then((data)){

console.log(data)// it will print anubhav

}

0
Subscribe to my newsletter

Read articles from Anubhav Anand Rai directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Anubhav Anand Rai
Anubhav Anand Rai