简体   繁体   English

await 函数在进入下一行之前没有执行。 (异步/等待不起作用)

[英]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.我想同时调用 display 函数中的两个 API,在获取这些数据后,我想调用 getmoreData 函数中的另一个 API。 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.这就是为什么我使用 promises 和 async await 但是当我单击按钮然后 getmoreData 首先执行然后我获取 displayData 函数中的这两个 API 的数据的原因。 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.问题是您正在解决在fetch响应进来之前从displayData返回的承诺。

To fix that, you can skip the building of a new Promise and use Promise.all .要解决这个问题,您可以跳过新Promise的构建并使用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() )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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