【发布时间】:2019-12-18 10:45:08
【问题描述】:
我正在尝试调用 Trip Advisor API 并使用 async/await 函数返回一些数据。
async/await 函数定义在一个名为 req.js 的文件中,代码如下:
const findRest = async (reviews, closed) => {
const respond = await fetch(
"https://tripadvisor1.p.rapidapi.com/restaurants/list-by-latlng?limit=30¤cy=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 更改为 map 并且仍然没有返回任何内容。有人可以帮忙吗!
【问题讨论】:
-
对我来说似乎工作正常。我创建了一个StackBlitz 来重现该问题。它虽然抛出了问题(没有 API 密钥),所以承诺被拒绝并记录错误“无法在指定参数内提供结果”
-
它会抛出错误,因为没有 api 密钥,但是一旦我将 api 密钥插入代码中,同样的事情就会发生,控制台什么也不返回。
-
API 是否返回某些内容?把你的调试器放在
let data = await respond.json();的findRest函数上,看看这些东西是否真的给你一个结果 -
确实如此,我刚刚在控制台中运行了代码,似乎 const userClose 有问题。这似乎因为某种原因阻止了代码并且什么也不返回
-
不可能的。当我在没有 API 密钥的情况下对其进行测试时会显示错误,因此可以毫无问题地获取值。函数的输出是什么?您可以通过
const data = await findRest(userReviews, userClose); console.log(data);或findRest(userReviews, userClose).then((data) => console.log(data))提供它,因为您不使用异步/等待
标签: javascript ecmascript-6 async-await es6-promise addeventlistener