多么熟悉的两个关键字,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); } }