React Native之async/await的使用


多么熟悉的兩個關鍵字,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);
    }
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM