Promises in JavaScript
Code :
// resolve
// reject
// pending
console.log("We are at tutorial 39b");
// Pretend that this response is coming from the server
const students=[
{name:"Ram", subject:"JavaScript"},
{name:"Rohan", subject:"Machine Learning"}
]
function enrollStudent(student){
return new Promise(function(resolve, reject){
setTimeout(function(){
students.push(student);
console.log("Student has been enrolled");
const error=false;
if(!error){
resolve();
}
else{
reject();
}
}, 5000);
})
}
function getStudents(){
setTimeout(function(){
let str="";
students.forEach(function(student){
str+= `<li> ${student.name}</li>`
});
document.getElementById('students').innerHTML=str;
console.log("Students have been fetched");
}, 1000);
}
let newStudent={name:"Sunny", subject:"Python"}
enrollStudent(newStudent).then(getStudents).catch(function(){
console.log("Some error occured");
});
// function inside then is ran as - resolve()
// function inside catch is ran as - reject ()
// Output:
Comments
Post a Comment