[英]meteo.js:21 Uncaught SyntaxError: await is only valid in async function
I have a problem in my code I do not see the weather API appear in my code 我的代码中有问题我没有看到我的代码中出现了天气API
Uncaught SyntaxError: await is only valid in async function meteo.js:21
未捕获的SyntaxError:await仅在异步函数meteo.js中有效:21
if (WithIP) {
const ip = await fetch('https://api.ipify.org/?format=json%27')
.then(resultat => resultat.json())
.then(json => json.ip);
ville = await fetch("http://api.ipstack.com/json/' + ip + '?access_key=' + access_key")
.then(resultat => resultat.json())
.then(json => json.city);
} else {
ville = document.querySelector('#ville').textContent;
}
{
const meteo = await fetch('http://api.openweathermap.org/data/2.5/weather?q=Marseille&appid=33119b4a3fa1ad278805578d27ea15de&lang=fr&units=metric%27')
.then(resultat => resultat.json())
.then(json => json)
Here is a quote from Mozilla Developers : 以下是Mozilla开发人员的一句话:
An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.
异步函数可以包含一个等待表达式,该表达式暂停执行异步函数并等待传递的Promise的解析,然后恢复异步函数的执行并返回已解析的值。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
You can only use await
in an async
function - to avoid making your whole code an async
function, use IIFEs like so: 你只能在
async
函数中使用await
- 为了避免使你的整个代码成为async
函数,使用像这样的IIFE:
const ip = (async () => await fetch('https://api.ipify.org/?format=json%27'))();
Because you're still using .then
chaining, you could just remove the await
part completely and just use .then
for continuity. 因为你还在使用
.then
chaining,你可以完全删除await
部分,然后使用.then
来保持连续性。
fetch('https://api.ipify.org/?format=json%27').then(resultat => resultat.json()).then(...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.