多么熟悉的两个关键字,C#6中引入的两个关键字,能够很方便的将同步方法变为异步的react
ES6中一样引入的同名的关键字,连用法都同样(目前还没发现差别)git
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') }
结果github
a
b
a1
---------json
注意:react-native
在React中使用有一个不一样点异步
async componentWillMount() { console.log('a'); //获取本地存储的用户名和密码 let userInfo= await AppStorage.get(Constants.KeyNames_UserInfo); console.log('a1'); } render(){ console.log('b'); }
Cmponent中rende是在componentWillMount以后执行的,可是只要结果是:async
b
a
a1
只要生命周期函数变为函数
2.fetchfetch
通常咱们使用fetch的时候this
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); } }