I have this piece of code in React which calls the Dark Sky API and returns weather data for a specific day. Each request gets a particular date. Once the request is successful, I put the data in an array via setState. The code runs fine but each request runs asynchronously so the data gets pushed to the array in the order in which each call completes so it's not getting me an ordered day list. Here's the code:
loadPreviousMonth = async () => {
const current = {...this.state};
for (let i=30; i >= 1; i--) {
const date = new Date();
const previousDay = Math.floor(date.setDate(date.getDate() - i) / 1000);
const url = `/api/darksky?latitude=${current.latitude}&longitude=${current.longitude},${previousDay}`;
await darkSky(url, this.onTimeRequestSuccess, this.onError);
}
}
Thanks!