reactjs:解析错误:await是保留字

时间:2018-10-24 11:35:11

标签: javascript async-await

./ src / App.js

  

第15行:解析错误:await是保留字

13 |   getWeather = async=()=>{
14 | 
15 |     const api_call = await fetch('http://api.openweathermap.org/data/2.5/weather?q=Manchester,uk&appid=${API_KEY}');
   |                      ^
16 | 
17 |     const data = await api_call.json();

如何摆脱这个错误?

3 个答案:

答案 0 :(得分:1)

由于您是这种语言的新手,所以建议您不要使用这种方式。叫做arrow function

async () => { /*...*/ };

// same to

async function () { /*...*/ };

并与参数一起使用:

async (param_1, param_2) => { /*...*/ };

// same to

async function (param_1, param_2) { /*...*/ };

在您的情况下,问题可能来自

// remove "=" character after "async" keyword here
async=()=> { /*...*/ }

希望这会有所帮助!

答案 1 :(得分:0)

正如其他人所述,您有一个不必要的=符号。 async关键字后面不需要=符号,您可能会认为它是该函数的一种“标签”。由于该函数未正确标记为async,因此代码不喜欢在函数正文中使用await关键字。

以下是一些片段,以说明两者之间的区别:

const getWeather = async=()=>{ 
 const api_call = await fetch('http://api.openweathermap.org/data/2.5/weather?q=Manchester,uk&appid=${API_KEY}');
 
  const data = await api_call.json();
}

上面的代码试图将getWeatherasync都设置为您定义的函数。以下是一些更多的示例来演示:

const test = aNonKeyword = () => {
  console.log('test')
}

const testTwo = anotherNonKeyword = 'A Test String'

var var1 = var2 = var3 = 1

console.log(test)
console.log(aNonKeyword)
console.log(testTwo)

console.log(var1)
console.log(var2)
console.log(var3)

...这是实际的工作版本:

const getWeather = async () => { 
 const api_call = await fetch('http://api.openweathermap.org/data/2.5/weather?q=Manchester,uk&appid=${API_KEY}');
 
  const data = await api_call.json();
}

答案 2 :(得分:0)

第13行试图将箭头功能重新分配给保留变量“ async”。从右到左执行是错字,在J中要记住的一个关键。