【发布时间】:2017-10-31 09:03:13
【问题描述】:
我想使用 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));
谢谢!
编辑
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 在第二个之前执行...
【问题讨论】:
标签: loops asynchronous react-native fetch state