2016-07-05 15 views
2

Im Codebeispiel versuche ich setState() mit einem Array von Promise Objekten aufzurufen. Die Daten (Koordinaten) müssen von einem externen REST-Service abgerufen werden.Einstellung des Status mit async/await in React

Gibt es ein gemeinsames Muster dafür in React?

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; 
    } 

Das resultierende Array enthält Versprechen Objekte und die Zustandsaktualisierungs Ergebnisse in Fehler:

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

Sehen Sie sich https://StackOverflow.com/questions/37576685/using-async-await-with-a-foreach-loop an – Bergi

Antwort

2

Das ist eigentlich ziemlich einfach. Sie müssen die Array von Versprechungen setState Sie vorbei auszupacken, da es nicht bekannt ist, versprechen:

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

Die Promise.all Teil wartet auf das gesamte Array und die await auspackt es für setState.