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(resolvereject){
        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

Popular posts from this blog

MongoDB shell version v4.4.4 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: No connection could be made because the target machine actively refused it. : connect@src/mongo/shell/mongo.js:374:17 @(connect):2:6 exception: connect failed exiting with code 1

Creating Your Portfolio Website

First Backend Website