[英]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.