gpt4 book ai didi

javascript - 异步等待函数未在事件监听器中执行

转载 作者:行者123 更新时间:2023-11-30 13:45:37 29 4
gpt4 key购买 nike

我正在尝试调用 Trip Advisor API 并使用异步/等待函数返回一些数据。

async/await 函数定义在名为 req.js 的文件中,代码如下:

const findRest = async (reviews, closed) => {
const respond = await fetch(
"https://tripadvisor1.p.rapidapi.com/restaurants/list-by-latlng?limit=30&currency=EUR&distance=2&lunit=km&lang=en_US&latitude=53.3498&longitude=-6.2603",
{
method: "GET",
headers: {
"x-rapidapi-host": "tripadvisor1.p.rapidapi.com",
"x-rapidapi-key": "x-rapidapi-key"
}
}
);

if (respond.status === 200) {
let data = await respond.json();
let newData = await data.data;

let data1 = await newData.filter(
review => parseInt(review.num_reviews) >= reviews
);
let data2 = await data1.filter(close => close.is_closed == closed);
return data2;
} else {
throw new Error("Could not provide results within specified parameters");
}
};

当事件监听器通过单击小窗体中的按钮触发时将调用它。此代码位于名为 app.js 的文件中,如下所示:

document.getElementById("subButton").addEventListener("click", function(e) {
const userReviews = parseInt(document.querySelector(".userRev").value);
const userClose = document.querySelector(".userClose").value;

e.preventDefault();
console.log("click");
console.log(e.target.id);

findRest(userReviews, userClose)
.then(data =>
data.forEach(element =>
console.log(
`${element.name} matches your search criterea and is located at ${element.address}
To make a booking, please call ${element.phone}`
)
)
)
.catch(err => console.log(err));
});

此处供引用的是 HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>API Tester</title>
<meta name="author" content="Phil My Glass" />
<meta
name="description"
content="An app to help me practice my API calling"
/>
</head>
<body>
<header>
<h1>What Restaurant?</h1>
</header>
<main>
<form id="form">
<input id="userRev" class="userRev" /><br />
<input id="userClose" class="userClose" />
<button id="subButton" class="subButton" type="submit">Find!</button>
</form>
</main>
</body>
<script src="req.js" type="text/Javascript"></script>
<script src="app.js" type="text/Javascript"></script>
</html>

当我在 app.js 文件中但在事件监听器外部运行 findRest 函数并将参数作为静态数据传递时,它只执行查找并将所有请求的数据打印到控制台。一旦我尝试在事件监听器中运行它,就什么也没有发生。没有返回的数据打印,没有错误,这让我很困惑。

就像我说的,它在事件监听器之外工作正常,但我已经尝试将 forEach 更改为映射,但仍然没有返回任何内容。有人可以帮忙吗!

最佳答案

回答

从评论和您的回复来看:没有任何事情发生的原因是因为数据是一个空数组。Array.forEach(callback) 仅在数组包含元素时执行回调。

它可能为空的原因是 restaurant.is_closed 的过滤器可能需要一个 bool 值,而您传入​​的是一个字符串(输入元素的值是一个字符串)。

最好使用复选框来查看它是否被选中。否则,您必须查看字符串输入是否匹配“true”或“false”。

代码本身

findRest 包含不必要的等待。您应该将其定义为

async function findRest(reviews, closed) {
const response = await fetch(
"https://tripadvisor1.p.rapidapi.com/restaurants/list-by-latlng?limit=30&currency=EUR&distance=2&lunit=km&lang=en_US&latitude=53.3498&longitude=-6.2603",
{
method: "GET",
headers: {
"x-rapidapi-host": "tripadvisor1.p.rapidapi.com",
"x-rapidapi-key": "x-rapidapi-key"
}
}
);

if (response.status === 200) {
// The only async call is casting the response to a JavaScript object
const json = await response.json();
console.log(json);
const data = json.data;
// Filtering the array is not async
return data.filter((restaurant) => {
// Adding some additional debugs to prove my hypothesis right
const hasEnoughReviews = restaurant.num_review >= reviews;
const isClosed = restaurant.is_closed === closed;
console.log(`review debug: ${typeof restaurant.num_review}, ${typeof reviews} -> output: ${hasEnoughReviews}`);
console.log(`closed debug: ${typeof restaurant.is_closed}, ${typeof closed} -> output: ${isClosed}`)
return hasEnoughReviews && isClosed

})
} else {
throw new Error("Could not provide results within specified parameters");
}
}

您还可以在 eventListener 回调中使用 async/await,创建更简洁的代码

document.getElementById("subButton").addEventListener("click", async (e) => {
const userReviews = parseInt(document.querySelector(".userRev").value);
// Judging by the filter in the findRest, this should be a boolean?
const userClose = document.querySelector(".userClose").value;

e.preventDefault();
console.log("click");
console.log(e.target.id);

try {
const restaurants = await findRest(userReviews, userClose);
// I think your issue is that restaurants is an empty array
console.log(restaurants)
restaurants.forEach(restaurant => {
console.log(`${restaurant.name} matches your search criterea and is located at ${restaurant.address}
To make a booking, please call ${restaurant.phone}`)
})
} catch (err) {
console.log(err)
}
});

关于javascript - 异步等待函数未在事件监听器中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59390307/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com