2016-07-05 13 views
2

コード例では、Promiseオブジェクトの配列でsetState()を呼び出しようとしています。データ(座標)は、外部のRESTサービスからフェッチする必要があります。状態をasync/awaitで設定してください

Reactでこれを行う一般的なパターンはありますか?

ANNOTATIONS: [Promise, Promise, Promise, Promise, Promise, Promise, Promise] 
ExceptionsManager.js:70 Warning: Failed prop type: Required prop `annotations[0].latitude` was not specified in `MapView`. 
    in MapView (at index.js:204) 
    in SampleAppInspection (at renderApplication.ios.js:90) 
    in RCTView (at View.js:348) 
    in View (at renderApplication.ios.js:65) 
    in RCTView (at View.js:348) 
    in View (at renderApplication.ios.js:64) 
    in AppContainer (at renderApplication.ios.js:89) 
+0

https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – Bergi

答えて

2

これは実際にはかなり簡単である:

async getLocations(locations) { 
    var annotations = locations.map(this.getLocation); 
    console.log("ANNOTATIONS:", annotations); 
    this.setState({ 
     annotations:annotations 
    }); 
    } 

    async getLocation(location) { 
     try { 
     let res = await Geocoder.geocodeAddress(location.address); 
     return (
      { 
       latitude: res[0].position.lat, 
       longitude: res[0].position.lng, 
       title: location.address, 
       subtitle: location.provider, 
      } 
     ); 
     } 
     catch(err) { 
     console.log("Error fetching geodata",err); 
     } 
     return null; 
    } 

得られた配列は、プロミスオブジェクトとエラーの状態更新結果を含みます。あなたはそれを認識して約束されていないので、あなたがsetStateを渡している約束の配列をアンラップする必要があります。

this.setState({ 
    annotations: await Promise.all(annotations) 
}); 

Promise.all部分は、アレイ全体を待ち、のawaitはsetStateのためにそれをアンラップ。

関連する問題