[英]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>
我想同时调用 display 函数中的两个 API,在获取这些数据后,我想调用 getmoreData 函数中的另一个 API。 这就是为什么我使用 promises 和 async await 但是当我单击按钮然后 getmoreData 首先执行然后我获取 displayData 函数中的这两个 API 的数据的原因。 我的代码是否有问题,如果没有,那么为什么我没有得到想要的结果。
问题是您正在解决在fetch
响应进来之前从displayData
返回的承诺。
要解决这个问题,您可以跳过新Promise
的构建并使用Promise.all
。 下面是一个例子:
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]);
}
此外,您有一些重复的代码,您可以将其重构为:
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));
}
或者,您可以在第一个解析时使第二个函数成为回调:
async function getAll(){
await displayData().then( () => getmoreData() )
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.