Javascript 在 React Native 中使用 async/await 时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36527490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:12:01  来源:igfitidea点击:

Error using async/await in React Native

javascriptreact-nativebabeljsecmascript-next

提问by MusicMan

When trying to use async/await in react-native, I am getting the following error:

尝试在 react-native 中使用 async/await 时,出现以下错误:

    uncaught error Error: SyntaxError: /Users/senthilsivanath/Documents/MusicTulip/index.ios.js: Unexpected token (50:23)
  48 |   renderScene: function(route,nav) {
  49 |     try {
  50 |          const response = await signIn.isLoggedIn();

My .babelrcfile is:

我的.babelrc文件是:

{ "presets": ["react-native", "es2015", "babel-preset-stage-3"] }

回答by radiovisual

You might just be missing the asynckeyword on line 48.

您可能只是遗漏了async第 48 行的关键字。

Update your code to use the asynckeyword before the functionkeyword:

更新您的代码以在async关键字之前使用function关键字:

renderScene: async function(route, nav) {
    try {
        const response = await signIn.isLoggedIn();
        // ...

Or when using an arrow function, put the asynckeyword before the parameter list:

或者在使用箭头函数时,将async关键字放在参数列表之前:

 renderScene: async (route, nav) => {
        try {
            const response = await signIn.isLoggedIn();

In JavaScript, the asynckeyword is a decorator that warns the runtime that the attached enclosure will use the awaitkeyword, so you always see them used together. Which is why you will hear people refer to this syntax as the async/awaitsyntax.

在 JavaScript 中,async关键字是一个装饰器,它警告运行时附加的外壳将使用该await关键字,因此您总是会看到它们一起使用。这就是为什么您会听到人们将此语法称为async/await语法的原因。

Simply put:You can't use awaitwithout async.

简单地说:你不能使用await没有async

Edit:If you are declaring this inside of a class, then just be sure that your syntax is correct:

编辑:如果您在类中声明它,那么请确保您的语法正确

class MusicTulip extends Component {
    async renderContent() {
        const response = await signIn.isLoggedIn();
    }
 }

Hope this helps!

希望这可以帮助!