简体   繁体   中英

await function is not executing before going on next line. (Async/await not working)

<!DOCTYPE html>
<html>
    <head>
        <title>Async/Await</title>
    </head>
    <body>
        <button id="getData">getData</button>
    <script>
        document.getElementById("getData").addEventListener("click", getAll);
        function displayData(){
            return new Promise((res, rej)=>{
                fetch("https://jsonplaceholder.typicode.com/posts").then((res)=>{
                    return res.json();
                }).then((data)=>{
                    console.log(data);
                }).catch((err)=>{
                    rej(err);
                });
                fetch("https://jsonplaceholder.typicode.com/users").then((res)=>{
                    return res.json();
                }).then((res)=>{
                    console.log(res);
                }).catch((err)=>{
                    rej(err);
                })
                res();
            });
        }

        function getmoreData(){
            fetch("https://reqres.in/api/users/2").then((res)=>{
                return res.json();
            }).then((data)=>{
                console.log(data.data);
            }).catch((err)=>{
                console.log(err);
            });
        }

        async function getAll(){
            await displayData();
            getmoreData();
        }
    </script>
    </body>
</html>

I want to call two APIs at the same time which is in display function and after getting those data, I want to call another API which is in getmoreData function. That's why I used promises and async await but when I click button then getmoreData execute first and then I get data of those two APIs which is in displayData function. Is there something wrong in my code and if not then why I am not getting desired result.

The problem is that you're resolving the promise that you return from displayData before the fetch responses come in.

To fix that, you can skip the building of a new Promise and use Promise.all . Here is an example:

function displayData(){
    const call1 = fetch("https://jsonplaceholder.typicode.com/posts").then((res)=>{
        return res.json();
    }).then((data)=>{
        console.log(data);
        return data;
    });
    const call2 = fetch("https://jsonplaceholder.typicode.com/users").then((res)=>{
        return res.json();
    }).then((res)=>{
        console.log(res);
        return res;
    });
    return Promise.all([call1, call2]);
}

Also, you have some repeating code, you can refactor this to:

function getAndPrintData(url) {
  return fetch(url)
    .then(rsp => rsp.json())
    .then(json => {
      console.log(json);
      return json;
    });
}

const base = "https://jsonplaceholder.typicode.com/";
const urls = [`${base}posts`, `${base}users`];

function displayData() {
  return PromiseAll(urls.map(getAndPrintData));
}

Optionally you could make the second function to be a call back when the first resolve:

async function getAll(){
    await displayData().then( () => getmoreData() )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM