How to use await key word on react native?

后端 未结 4 1401
[愿得一人]
[愿得一人] 2020-12-09 07:28

I tried to use await/async on react native,but I got unexpected token error.

I added the code blow in my javascript source file:

var value = await As         


        
相关标签:
4条回答
  • 2020-12-09 07:46

    Do I need to add some configuration to use async/await?

    Yes. async is still not a finalized part of the specification; they're currently considered "Stage 3" (Candidate).

    You can enable all Stage 3 language proposals in your .babelrc by using the stage-3 preset. Alternatively, you can add just the async plugin.

    0 讨论(0)
  • 2020-12-09 07:57

    I'm using async/await in my react native app and didn't have to do anything to configure or enable it in my project. My usage takes the form of...

    async getCache(key){
        try{
            let value = await AsyncStorage.getItem(key);
            return value.json();
        }
        catch(e){
            console.log('caught error', e);
            // Handle exceptions
        }
    
    }
    

    Note: If you use an await inside a function that is not explicitly declared with async, you'll end up with an Unexpected token syntax error.

    0 讨论(0)
  • 2020-12-09 07:57

    If you have a .babelrc file in the root of your project, you need to add the "react-native" preset:

    npm i babel-preset-react-native --save-dev

    Then in your .babelrc file add the following:

    {
      "presets": ["react-native"]
    }
    

    More information here.

    0 讨论(0)
  • 2020-12-09 08:05

    After reading this comment on the react-native GitHub issues, the following worked for me:

    Add the following npm module:

    npm install babel-preset-react-native-stage-0 --save

    Add the following configuration to your .babelrc file:

    { presets: ['react-native-stage-0'] }

    Clear your cache:

    $ watchman watch-del-all
    $ ./node_modules/react-native/packager/packager.sh --reset-cache
    
    0 讨论(0)
提交回复
热议问题