i got a small problem with my promises.
This is my function:
public generateMealPlanForAWeek(myMealProfile: any, totalCalories:number):Promise<any> {
return new Promise(resolve => {
let mealplan:Array<any> = [];
for (let i = 1; i <= 7; i++) {
this.generateMealPlanForOneDay(myMealProfile, totalCalories).then(data => {
mealplan.push(data); // resolves much later
});
}
resolve(mealplan); // is resolved instant
})
}
My problem is, that "generateMealPlanForOneDay" is resolved later then the mealplan itself.
Mealplan is an array of objects (meals in this case).
When i want to save my mealplan, the mealplan is empty:
this.storage.set('Mealplan', JSON.stringify(mealplan)).then(....) // meal plan is Array[0]
Whats the best way to resolve all meals of my meal plan and then save it?
i got a small problem with my promises.
This is my function:
public generateMealPlanForAWeek(myMealProfile: any, totalCalories:number):Promise<any> {
return new Promise(resolve => {
let mealplan:Array<any> = [];
for (let i = 1; i <= 7; i++) {
this.generateMealPlanForOneDay(myMealProfile, totalCalories).then(data => {
mealplan.push(data); // resolves much later
});
}
resolve(mealplan); // is resolved instant
})
}
My problem is, that "generateMealPlanForOneDay" is resolved later then the mealplan itself.
Mealplan is an array of objects (meals in this case).
When i want to save my mealplan, the mealplan is empty:
this.storage.set('Mealplan', JSON.stringify(mealplan)).then(....) // meal plan is Array[0]
Whats the best way to resolve all meals of my meal plan and then save it?
Share Improve this question asked Dec 13, 2016 at 13:46 FarghoFargho 1,2775 gold badges15 silver badges31 bronze badges2 Answers
Reset to default 13You can use Promise.all
in this case.
public generateMealPlanForAWeek(myMealProfile: any, totalCalories:number):Promise<any> {
var mealPlans = [];
for (let i = 1; i <= 7; i++) {
mealPlans.push(this.generateMealPlanForOneDay(myMealProfile, totalCalories));
}
return Promise.all(mealPlans);
}
// later
generateMealPlanForAWeek(...).then(mealPlans => ...);
Instead of working with promises, you can also work with event streams.
The Reactive Extensions for JavaScript (RxJS, see https://github./ReactiveX/RxJS) makes it easy to react to event streams (Observable
s and their OnNext
events), or for instance to the end of an event stream (the OnCompleted
event), to collect the events and save their data.
Here's an interesting example: https://xgrommx.github.io/rx-book/content/getting_started_with_rxjs/creating_and_querying_observable_sequences/creating_and_subscribing_to_simple_observable_sequences.html