Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error using async/await in React Native

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

    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 .babelrc file is:

{ "presets": ["react-native", "es2015", "babel-preset-stage-3"] } 
like image 864
MusicMan Avatar asked Apr 10 '16 08:04

MusicMan


People also ask

Does await throw error?

If a promise resolves normally, then await promise returns the result. But in the case of a rejection, it throws the error, just as if there were a throw statement at that line. In real situations, the promise may take some time before it rejects. In that case there will be a delay before await throws an error.

How do I return async function error?

Async functions and async methods do not throw errors in the strict sense. Async functions and async methods always return a Promise, either resolved or rejected. You must attach then() and catch() , no matter what. (Or wrap the method inside try/catch ).

How do I get exceptions in await?

To catch an exception that an async task throws, place the await expression in a try block, and catch the exception in a catch block. Uncomment the throw new Exception line in the example to demonstrate exception handling. The task's IsFaulted property is set to True , the task's Exception.


1 Answers

You might just be missing the async keyword on line 48.

Update your code to use the async keyword before the function keyword:

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

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

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

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

Simply put: You can't use await without 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();     }  } 
like image 197
radiovisual Avatar answered Oct 05 '22 23:10

radiovisual