多么熟悉的兩個關鍵字,C#6中引入的兩個關鍵字,可以很方便的將同步方法變為異步的
ES6中同樣引入的同名的關鍵字,連用法都一樣(目前還沒發現差異)
constructor() { super(); this.A(); this.B(); } async A() { console.log('a') let userInfo= await AppStorage.get(Constants.KeyNames_UserInfo); console.log('a1') } B() { console.log('b') }
結果
a
b
a1
---------
注意:
在React中使用有一個不同點
async componentWillMount() { console.log('a'); //獲取本地存儲的用戶名和密碼 let userInfo= await AppStorage.get(Constants.KeyNames_UserInfo); console.log('a1'); } render(){ console.log('b'); }
Cmponent中rende是在componentWillMount之后執行的,但是只要結果是:
b
a
a1
只要生命周期函數變為
2.fetch
一般我們使用fetch的時候
getMoviesFromApiAsync() { return fetch('http://facebook.github.io/react-native/movies.json') .then((response) => response.json()) .then((responseJson) => { return responseJson.movies; }) .catch((error) => { console.error(error); }); }
但是也可以使用ES7中的async/await來實現,這樣完全是同步的用法了
// 注意這個方法前面有async關鍵字 async getMoviesFromApi() { try { // 注意這里的await語句,其所在的函數必須有async關鍵字聲明 let response = await fetch('http://facebook.github.io/react-native/movies.json'); let responseJson = await response.json(); return responseJson.movies; } catch(error) { console.error(error); } }