Home  • Programming • JavaScript

Sending asynchronous ajax request through Promise API in JavaScript

 <script>
      //Show()
      //ajax1();

      async function Show(){
        let result= await fetch("data.txt");
        let r=await result.text();
        console.log(r);           
        document.body.textContent=r;
     }
    
     function ajax(){
        fetch('./data.json').then(response => {
           return response.json();
        }).then(data => {
           console.log(data);   
        }).catch(err => {
           console.lgo(err);
        }); 
    }

    async function ajax1(){
        const response=await fetch("./data.json");
        let json=await response.json();
        console.log(json);
    }

//Parallel fetch requests
    async function fetchMultipleFiles() {
        const [dataRes, data1Res] = await Promise.all([
            fetch('./data.json'),
            fetch('./data2.json')
        ]);

        const students = await dataRes.json();
        const categories = await data1Res.json();

        return [students, categories];
    }
    
    fetchMultipleFiles().then(([students, categories]) => {
        console.log(students);
        console.log(categories);
    }).catch(error => {
      // /movies or /categories request failed
       console.log(error);
    });    

    </script>

Comments 0


Copyright © 2024. Powered by Intellect Software Ltd