Java script promise then catch methods

 
Promise create links between producing code and consuming code.
 
let promise= new Promise(function(resolve, reject){

});
 
This promise constructor will contain producing code and one function pass to this constructor and automatically call as promise object created.
 
resolve and reject arguments automatically passed to this function by java script itself.
 
  1. resolve(value)
    Call when job finished with value.
  2. reject(error)
    Call when job failed with the error object.

consuming code with these methods

  1. .then()
    To consume data.
  2. .catch()
    To consume errors
  3. .finally()
    Run always

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
</body>
</html>
<script>
    // data
    var groups=[
            {
                "id":1,
                "name":"HP"
            },
            {
                "id":2,
                "name":"DELL"
            }
    ];
    var products=[
    {
        "id":1,
        "group_id":1,
        "name":"HP Laptop"
    },
    {
        "id":2,
        "group_id":1,
        "name":"HP Mouse"
    },
    {
        "id":3,
        "group_id":2,
        "name":"Dell laptop"
    }
    ];

function loadGroup(id){
    return new Promise( (resolve, reject)=>{
        let group=groups.find(item=>{
            return item.id == id;
        })  
        resolve(group)
    } )
}

function loadProducts(id){
    return new Promise((resolve, reject)=>{
        let product=products.find(item=>{
            return item.group_id == id;
        })
        resolve(product);
    })        
}

loadGroup(1)
.then(group=>{
    console.log(group);
    return loadProducts(group.id)
})
.then(products=>console.log(products));

</script>

© 2016 - 2022, All Rights are Reserved.