【问题标题】:reactjs :Parsing error: await is a reserved wordreactjs:解析错误:await是保留字
【发布时间】:2019-03-28 19:23:49
【问题描述】:

./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();

我怎样才能摆脱这个错误?

【问题讨论】:

  • async 后面的多余 = 符号可能会破坏您的功能。
  • 错误出在函数的语法中,在 async 和函数 getWeather = async ()=>{ 之间有一个额外的=

标签: javascript async-await


【解决方案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=()=> { /*...*/ }

希望这会有所帮助!

【讨论】:

  • 你认为js新手不应该使用箭头函数吗?
  • @OliverRadini 是的,先生!对我来说,我们首先需要学习如何使用通用语法定义函数。然后,我们可以从箭头函数开始。从 ES5 到 ES6。
  • 我想也许我不同意,箭头函数的语法似乎不是这里的问题。我不确定箭头函数的语法一定比标准函数定义更难理解
  • @OliverRadini 同意!这只是我的意见。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    正如其他人所提到的,您有一个不必要的= 符号。 async 关键字后面不需要= 符号,您可能会将其视为函数的一种“标签”。由于该函数未正确标记为 async,因此代码不喜欢在函数体中包含 await 关键字。

    这里有一些sn-ps来说明区别:

    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();
    }

    【讨论】:

      猜你喜欢
      • 2019-03-05
      • 2019-01-06
      • 2021-11-18
      • 2017-05-24
      • 2019-08-03
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 2017-12-08
      相关资源
      最近更新 更多