2016-12-29 31 views
0

我試圖運行從官方react-native docs下面的代碼塊:無法獲得異步工作在反應母語

async function getMoviesFromApi() { 
    try { 
     let response = await fetch('https://facebook.github.io/react-native/movies.json'); 
     let responseJson = await response.json(); 
     return responseJson.movies; 
    } catch(error) { 
     console.error(error); 
    } 
    } 

當我嘗試運行此我得到的錯誤:

"Unexpected token, expected ((31:17)" 

如果我刪除了function關鍵字,它工作正常。

如果我使用函數關鍵字或不使用它會有什麼不同?是因爲我在課堂上使用它嗎?它在文檔中的哪個位置表明了這一點?它是在反應原生文檔還是JavaScript文檔中?我似乎無法找到它,儘管我可能在尋找錯誤的東西。

我使用的反應母語:0.38.0(有反應母語-CLI:1.2.0)

+0

是什麼版本的JS? [它在Babel中有效](http://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=true&presets=latest&experimental=false&loose=false&spec=false&code=async%20function%20getMoviesFromApi()%20%7B%0D%0A %20%20try%20%7B%0D 0A%%20%20%20%20let%20response%20%3D%20await%20fetch(的「https%3A%2F%2Ffacebook.github.io%2Freact天然%2Fmovies。 JSON')%3B%0D 0A%%20%20%20%20let%20responseJson%20%3D%20await%20response.json()%3B%0D 0A%%20%20%20%20return%20responseJson.movi​​es%圖3B%0D 0A%%20%20%7D%20catch(誤差)%20%7B%0D 0A%%20%20%20%20console.error(誤差)%3B%0D 0A%%20%20%7D% 0D 0A%%7D&操場=真)。 – 4castle

回答

3

Is it because I am using it in a class?

可能。在一類方法聲明的語法是

class Foo { 
    method() {} 
} 

class Foo { 
    function method() {} 
} 

因此聲明異步方法

class Foo { 
    async method() {} 
} 

Where in the documentation does it indicate this? Is it in the react-native documentation or the JavaScript documentation?

它的JavaScript。 React是一個框架/庫,而不是一種語言。你使用的所有語法都是JavaScript(當然除了JSX,但這不是特定於React的)。

查看MDN documentation about classe s。