React Native之async/await的使用

多麼熟悉的兩個關鍵字,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);
    }
  }
相關文章
相關標籤/搜索