Async and await in javascript

 
These two keyword make java script promise more simple and easy to use.
 
The function include async means it will return promise always, and await keyword wait until promise return the result
 
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>
    "use strict"
    // 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);
    })        
}

let loadData= async ()=>{
    let group = await loadGroup(1);
    console.log(group);

    let products = await loadProducts(group.id);
    console.log(products);
}
loadData();

</script>
© 2016 - 2022, All Rights are Reserved.