JavaScript Example (Program)
Learn Details

what is promise ?


promise method एक object है | जो feature में return होने वाले value को लौटाती है, लेकिन अभी नहीं |

Q. How to create Promise ?

Promise को create करने के लिए new promise() लिखा जाता है और उसके अंदर एक function create किया जाता है और उस functuion के दो parameter में resolve , reject keyword किया जाता है |

What is resolve () ?

resolve एक predefine method है जिसमें promise के resolve value को return कराने के लिए use किया जाता है |

What is reject () ?

reject एक predefine method है जिसमें promise के reject value या message को return कराने के लिए use किया जाता है |

Syntax for create "promise" :

Var_name = new Promise((resolve, reject)=>{
resolve(// here your statement for return resolve value)
reject(// here your statement for return reject value)
)}

Q. How to access Promise value ?

Promise को access करने के लिए then () method और catch () method को use किया जाता है है |

Q. What is then() ?

then method का use resolve value यानी true value को return करने के लिए किया जाता है |

Q. What is catch () ?

catch method का use reject value यानी false value को return करने के लिए किया जाता है |

Syntax for Access "promise" :

Promise_name.then((any_para_meter)=>{
//Here display resolve value using like console.log()
}).catch((any_para_meter)=>{
//Here display reject value using like console.log()
})

Example of promise



<script>     
//Teacher student ko ak Task (10+20 = ?) dete hain. aur wo student se kahte hain ko jo student Task compleate karega un student men 3 winner hoga aur use teacher prize denge 
    //To bahut se student bolte hain ki sir, Main Task compleate kar dungaa

  //NOTE - yaha pe  do log promise compleate kar rahe hain
       //1. Student = jinka promise hai (10+20) ko compleate kar denge
       //2. Teacher = Jinka Promise hai ki 3 Winner ko Prize denaa

  // Promise Create syntax
    //new Promise((resolve, reject)=>{})
  // .then((argument_for_resolve)=>{}).catch((argument_for_reject)=>{})

    let Task = 10 +20;
    let studentTask = new Promise((resolve, reject)=>{
      setTimeout(()=>{
        if(Task == 30){
          let winner_student = ["Ram Kumar", "Suresh Sinha", "Mayank Sharma"]
          resolve(winner_student)
        }
        else{

        }
      },3000)

    })

    let teacherpromise = (winner)=>{
      return new Promise((resolve, reject)=>{
        setTimeout(()=>{
          let prize = {
            first : "Laptop",
            second : "Mobile",
            third : "Camera"
          }
          resolve(`
            ${winner[0]} is First Winner and his Prize is ${prize.first}
            ${winner[1]} is Second Winner and his Prize is ${prize.second}
            ${winner[2]} is Third Winner and his Prize is ${prize.third}`)
        },3000) 
      })
    }

    studentTask.then((x)=>{
      
      console.log(x)
      teacherpromise(x).then((prz)=>{
        console.log(prz)
      })


    }).catch((y)=>{
      console.log(y)
    })
</script>