2017-10-31 7 views
0

google APIを使用していくつかの期間を取得したいのですが、私の状態で取得した値を入れることはできません。 これは私のコードです:ループ内にフェッチした状態のネイティブ・ファクト・セット値を返す

for (i = 0; i < this.state.nbLieux; i++) { 
     const index = i; 
     fetch(`https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&mode=walking&origins=${this.state.location.coords.latitude},${this.state.location.coords.longitude}&destinations=${this.state.lieux[index].lattitude},${this.state.lieux[index].longitude}&key=AIzaSyBqonK_W7A4chMiVoJTTs2cTU65XBcCh68`) 
     .then((response) => response.json()) 
     .then((responseJson) => { 
      Duree[index] = responseJson.data 
     }) 
     .catch((error) => { 
      console.warn(error); 
     }) 
     .done(); 
    } 
    this.setState({Duree}); 
    console.log('salut'+JSON.stringify(this.state.Duree)); 

ありがとう! EDIT

this.myFunction().then((Duree) => { 
      console.log(Duree) 
     }); 

myFunction() { 
    return new Promise((resolve, reject) => { 
     let fetches = []; 
     let Duree = []; 
     for(let i = 0; i < this.state.nbLieux; i++) { 
      fetches.push(
       fetch(`https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&mode=walking&origins=${this.state.location.coords.latitude},${this.state.location.coords.longitude}&destinations=${this.state.lieux[i].lattitude},${this.state.lieux[i].longitude}&key=AIzaSyBqonK_W7A4chMiVoJTTs2cTU65XBcCh68`) 
       .then((response) => response.json()) 
       .then((responseJson) => { 
        console.log(JSON.stringify(responseJson)); 
        Duree[i] = responseJson; 
       }).catch((error) => { 
        console.warn(error); 
       }).done() 
      ) 
     } 
     Promise.all(fetches).then(() => { 
      resolve(Duree); 
     }) 
    }); 
} 

しかし、コンソールに、私は最初にconsole.logフェッチにおける第二の前に実行していることがわかります

...

答えて

0

約束でそれをラップし、LETキーワードを使用es6の場合は、es5の場合はclosureを使用します。そうですね...

myFunction() { 
    return new Promise((resolve, reject) => { 

     let fetches = []; 
     let arr = []; 

     for(let i = 0; i < 20; i++) { 
     fetches.push(
      fetch("https://slack.com/api/api.test") 
     .then((data) => data.json()) 
     .then((dataJson) => { 
      arr[i] = dataJson; 
     }) 
     ) 
     } 

     Promise.all(fetches).then(() => { 
     resolve(arr); 
     }) 

    }); 
    } 

    myFunction().then((data) => { 
     console.log(data); 
    }) 

テスト済みの作品は問題ありません。これはまた、Chromeではconsole.log ...

enter image description here

で、必ず "nbLieux" の状態が変化していないことを確認します。そうであれば、forループのすぐ上に別のlet変数を使用してください: "let num = this.state.nbLieux"

+0

こんにちはVocoJaxさん、あなたの答えをありがとう、私はあなたのコードを試しましたが、私の編集を見て、私が何を試みたかを見てください。 –

+0

私は私の答えを編集しました。それはまったく変わっていませんが、私はそれをテストしています。あなたのAPI文字列はおそらく壊れていますか? – VocoJax

関連する問題