Not sure how to populate an array within a method that has Promises within it





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I have a method that performs some basic mathematical calculations in my Ionic app after fetching data from SQLite DB. I want to show these results on a page but the problem is that I am not sure how to put all these calculated values in an object array.



I tried following but the editor is complaining about not resolving promises. To me it looks like I already resolved them by extracting a numeric value from each and assigning them to local variables such as grossMarketable, aphMarketable, amountSold and totalContractDollarAmount.



home.ts



private calculate() {
console.log("**********Starting calculations now.....");
let calculations: CalcModel = ;
for (let i = 0; i < this.userCropTxModels.length; i++) {
let userCropTxModel = this.userCropTxModels[i];
console.log("userCropTxModel: " + userCropTxModel);

let grossMarketable = this.userCropProvider.getGrossMarketableByCropId(userCropTxModel.cropId)
.then(grossMarketable => {
console.log("grossMarketable: " + grossMarketable);
return grossMarketable;
})
.catch((e) => console.error(JSON.stringify(e)));

let aphMarketable = this.userCropProvider.getAPHMarketableByCropId(userCropTxModel.cropId)
.then(aphMarketable => {
console.log("aphMarketable: " + aphMarketable);
})
.catch((e) => console.error(JSON.stringify(e)));

let amountSold = this.userContractProvider.getTotalContractedBushelsByCropId(userCropTxModel.cropId)
.then(amountSold => {
console.log("amountSold: " + amountSold);
})
.catch((e) => console.error(JSON.stringify(e)));

let totalContractDollarAmount = this.userContractProvider.getTotalContractDollarAmountByCropId(userCropTxModel.cropId)
.then(totalContractDollarAmount => {
console.log("totalContractDollarAmount: " + totalContractDollarAmount);
})
.catch((e) => console.error(JSON.stringify(e)));

console.log("grossMarketable: " + grossMarketable);
console.log("aphMarketable: " + aphMarketable);
console.log("amountSold: " + amountSold);
console.log("totalContractDollarAmount: " + totalContractDollarAmount);

/**************************************************
//THE EDITOR IS SHOWING RED MARKS BELOW
***********************************************/
calculations.push({
cropName: 'Corn',
grossMarketable: grossMarketable,
grossMarketable: grossMarketable,
amountSold: amountSold,
totalContractDollarAmount: totalContractDollarAmount
});
}
console.log("calculations: " + calculations);
}


user-crop.ts (code snippet of UserCropProvider)



getGrossMarketableByCropId(cropId: number): Promise<number> {
return this.databaseProvider.getDatabase().then(database => {
return database.executeSql(SQL_SELECT_GROSS_MARKETABLE_BY_CROP_ID, [cropId])
.then((data) => {
let grossMarketable: number = 0;
for (let i = 0; i < data.rows.length; i++) {
grossMarketable = data.rows.item(i).GROSS_MARKETABLE
}
return grossMarketable;
});
});
}


CalcModel.ts



export interface CalcModel {
cropName: string;
grossMarketable: number;
aphMarketable: number;
amountSold: number;
totalContractDollarAmount: number;
}









share|improve this question























  • The promises are not resolved. To write synchronous-looking code with promises, you can use async/await keywords. Alternatively use a single Promise.all(...) callback to ensure your 4 promises are resolved by array time

    – ne1410s
    Jan 3 at 6:01











  • How do I get the numeric value from that promise and assign it to the interface's variable? That's where I am confused most.

    – user2325154
    Jan 3 at 6:03






  • 1





    everything in home.ts is ASYNC, you need to make sure that all of the promises are resolved before you start to push data inside calculations array. as @ne1410s said you can use promise.all() or forkjoin() to achieve that

    – Mohit Patil
    Jan 3 at 6:11


















0















I have a method that performs some basic mathematical calculations in my Ionic app after fetching data from SQLite DB. I want to show these results on a page but the problem is that I am not sure how to put all these calculated values in an object array.



I tried following but the editor is complaining about not resolving promises. To me it looks like I already resolved them by extracting a numeric value from each and assigning them to local variables such as grossMarketable, aphMarketable, amountSold and totalContractDollarAmount.



home.ts



private calculate() {
console.log("**********Starting calculations now.....");
let calculations: CalcModel = ;
for (let i = 0; i < this.userCropTxModels.length; i++) {
let userCropTxModel = this.userCropTxModels[i];
console.log("userCropTxModel: " + userCropTxModel);

let grossMarketable = this.userCropProvider.getGrossMarketableByCropId(userCropTxModel.cropId)
.then(grossMarketable => {
console.log("grossMarketable: " + grossMarketable);
return grossMarketable;
})
.catch((e) => console.error(JSON.stringify(e)));

let aphMarketable = this.userCropProvider.getAPHMarketableByCropId(userCropTxModel.cropId)
.then(aphMarketable => {
console.log("aphMarketable: " + aphMarketable);
})
.catch((e) => console.error(JSON.stringify(e)));

let amountSold = this.userContractProvider.getTotalContractedBushelsByCropId(userCropTxModel.cropId)
.then(amountSold => {
console.log("amountSold: " + amountSold);
})
.catch((e) => console.error(JSON.stringify(e)));

let totalContractDollarAmount = this.userContractProvider.getTotalContractDollarAmountByCropId(userCropTxModel.cropId)
.then(totalContractDollarAmount => {
console.log("totalContractDollarAmount: " + totalContractDollarAmount);
})
.catch((e) => console.error(JSON.stringify(e)));

console.log("grossMarketable: " + grossMarketable);
console.log("aphMarketable: " + aphMarketable);
console.log("amountSold: " + amountSold);
console.log("totalContractDollarAmount: " + totalContractDollarAmount);

/**************************************************
//THE EDITOR IS SHOWING RED MARKS BELOW
***********************************************/
calculations.push({
cropName: 'Corn',
grossMarketable: grossMarketable,
grossMarketable: grossMarketable,
amountSold: amountSold,
totalContractDollarAmount: totalContractDollarAmount
});
}
console.log("calculations: " + calculations);
}


user-crop.ts (code snippet of UserCropProvider)



getGrossMarketableByCropId(cropId: number): Promise<number> {
return this.databaseProvider.getDatabase().then(database => {
return database.executeSql(SQL_SELECT_GROSS_MARKETABLE_BY_CROP_ID, [cropId])
.then((data) => {
let grossMarketable: number = 0;
for (let i = 0; i < data.rows.length; i++) {
grossMarketable = data.rows.item(i).GROSS_MARKETABLE
}
return grossMarketable;
});
});
}


CalcModel.ts



export interface CalcModel {
cropName: string;
grossMarketable: number;
aphMarketable: number;
amountSold: number;
totalContractDollarAmount: number;
}









share|improve this question























  • The promises are not resolved. To write synchronous-looking code with promises, you can use async/await keywords. Alternatively use a single Promise.all(...) callback to ensure your 4 promises are resolved by array time

    – ne1410s
    Jan 3 at 6:01











  • How do I get the numeric value from that promise and assign it to the interface's variable? That's where I am confused most.

    – user2325154
    Jan 3 at 6:03






  • 1





    everything in home.ts is ASYNC, you need to make sure that all of the promises are resolved before you start to push data inside calculations array. as @ne1410s said you can use promise.all() or forkjoin() to achieve that

    – Mohit Patil
    Jan 3 at 6:11














0












0








0








I have a method that performs some basic mathematical calculations in my Ionic app after fetching data from SQLite DB. I want to show these results on a page but the problem is that I am not sure how to put all these calculated values in an object array.



I tried following but the editor is complaining about not resolving promises. To me it looks like I already resolved them by extracting a numeric value from each and assigning them to local variables such as grossMarketable, aphMarketable, amountSold and totalContractDollarAmount.



home.ts



private calculate() {
console.log("**********Starting calculations now.....");
let calculations: CalcModel = ;
for (let i = 0; i < this.userCropTxModels.length; i++) {
let userCropTxModel = this.userCropTxModels[i];
console.log("userCropTxModel: " + userCropTxModel);

let grossMarketable = this.userCropProvider.getGrossMarketableByCropId(userCropTxModel.cropId)
.then(grossMarketable => {
console.log("grossMarketable: " + grossMarketable);
return grossMarketable;
})
.catch((e) => console.error(JSON.stringify(e)));

let aphMarketable = this.userCropProvider.getAPHMarketableByCropId(userCropTxModel.cropId)
.then(aphMarketable => {
console.log("aphMarketable: " + aphMarketable);
})
.catch((e) => console.error(JSON.stringify(e)));

let amountSold = this.userContractProvider.getTotalContractedBushelsByCropId(userCropTxModel.cropId)
.then(amountSold => {
console.log("amountSold: " + amountSold);
})
.catch((e) => console.error(JSON.stringify(e)));

let totalContractDollarAmount = this.userContractProvider.getTotalContractDollarAmountByCropId(userCropTxModel.cropId)
.then(totalContractDollarAmount => {
console.log("totalContractDollarAmount: " + totalContractDollarAmount);
})
.catch((e) => console.error(JSON.stringify(e)));

console.log("grossMarketable: " + grossMarketable);
console.log("aphMarketable: " + aphMarketable);
console.log("amountSold: " + amountSold);
console.log("totalContractDollarAmount: " + totalContractDollarAmount);

/**************************************************
//THE EDITOR IS SHOWING RED MARKS BELOW
***********************************************/
calculations.push({
cropName: 'Corn',
grossMarketable: grossMarketable,
grossMarketable: grossMarketable,
amountSold: amountSold,
totalContractDollarAmount: totalContractDollarAmount
});
}
console.log("calculations: " + calculations);
}


user-crop.ts (code snippet of UserCropProvider)



getGrossMarketableByCropId(cropId: number): Promise<number> {
return this.databaseProvider.getDatabase().then(database => {
return database.executeSql(SQL_SELECT_GROSS_MARKETABLE_BY_CROP_ID, [cropId])
.then((data) => {
let grossMarketable: number = 0;
for (let i = 0; i < data.rows.length; i++) {
grossMarketable = data.rows.item(i).GROSS_MARKETABLE
}
return grossMarketable;
});
});
}


CalcModel.ts



export interface CalcModel {
cropName: string;
grossMarketable: number;
aphMarketable: number;
amountSold: number;
totalContractDollarAmount: number;
}









share|improve this question














I have a method that performs some basic mathematical calculations in my Ionic app after fetching data from SQLite DB. I want to show these results on a page but the problem is that I am not sure how to put all these calculated values in an object array.



I tried following but the editor is complaining about not resolving promises. To me it looks like I already resolved them by extracting a numeric value from each and assigning them to local variables such as grossMarketable, aphMarketable, amountSold and totalContractDollarAmount.



home.ts



private calculate() {
console.log("**********Starting calculations now.....");
let calculations: CalcModel = ;
for (let i = 0; i < this.userCropTxModels.length; i++) {
let userCropTxModel = this.userCropTxModels[i];
console.log("userCropTxModel: " + userCropTxModel);

let grossMarketable = this.userCropProvider.getGrossMarketableByCropId(userCropTxModel.cropId)
.then(grossMarketable => {
console.log("grossMarketable: " + grossMarketable);
return grossMarketable;
})
.catch((e) => console.error(JSON.stringify(e)));

let aphMarketable = this.userCropProvider.getAPHMarketableByCropId(userCropTxModel.cropId)
.then(aphMarketable => {
console.log("aphMarketable: " + aphMarketable);
})
.catch((e) => console.error(JSON.stringify(e)));

let amountSold = this.userContractProvider.getTotalContractedBushelsByCropId(userCropTxModel.cropId)
.then(amountSold => {
console.log("amountSold: " + amountSold);
})
.catch((e) => console.error(JSON.stringify(e)));

let totalContractDollarAmount = this.userContractProvider.getTotalContractDollarAmountByCropId(userCropTxModel.cropId)
.then(totalContractDollarAmount => {
console.log("totalContractDollarAmount: " + totalContractDollarAmount);
})
.catch((e) => console.error(JSON.stringify(e)));

console.log("grossMarketable: " + grossMarketable);
console.log("aphMarketable: " + aphMarketable);
console.log("amountSold: " + amountSold);
console.log("totalContractDollarAmount: " + totalContractDollarAmount);

/**************************************************
//THE EDITOR IS SHOWING RED MARKS BELOW
***********************************************/
calculations.push({
cropName: 'Corn',
grossMarketable: grossMarketable,
grossMarketable: grossMarketable,
amountSold: amountSold,
totalContractDollarAmount: totalContractDollarAmount
});
}
console.log("calculations: " + calculations);
}


user-crop.ts (code snippet of UserCropProvider)



getGrossMarketableByCropId(cropId: number): Promise<number> {
return this.databaseProvider.getDatabase().then(database => {
return database.executeSql(SQL_SELECT_GROSS_MARKETABLE_BY_CROP_ID, [cropId])
.then((data) => {
let grossMarketable: number = 0;
for (let i = 0; i < data.rows.length; i++) {
grossMarketable = data.rows.item(i).GROSS_MARKETABLE
}
return grossMarketable;
});
});
}


CalcModel.ts



export interface CalcModel {
cropName: string;
grossMarketable: number;
aphMarketable: number;
amountSold: number;
totalContractDollarAmount: number;
}






javascript angular typescript ionic-framework promise






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 3 at 5:48









user2325154user2325154

1,78493880




1,78493880













  • The promises are not resolved. To write synchronous-looking code with promises, you can use async/await keywords. Alternatively use a single Promise.all(...) callback to ensure your 4 promises are resolved by array time

    – ne1410s
    Jan 3 at 6:01











  • How do I get the numeric value from that promise and assign it to the interface's variable? That's where I am confused most.

    – user2325154
    Jan 3 at 6:03






  • 1





    everything in home.ts is ASYNC, you need to make sure that all of the promises are resolved before you start to push data inside calculations array. as @ne1410s said you can use promise.all() or forkjoin() to achieve that

    – Mohit Patil
    Jan 3 at 6:11



















  • The promises are not resolved. To write synchronous-looking code with promises, you can use async/await keywords. Alternatively use a single Promise.all(...) callback to ensure your 4 promises are resolved by array time

    – ne1410s
    Jan 3 at 6:01











  • How do I get the numeric value from that promise and assign it to the interface's variable? That's where I am confused most.

    – user2325154
    Jan 3 at 6:03






  • 1





    everything in home.ts is ASYNC, you need to make sure that all of the promises are resolved before you start to push data inside calculations array. as @ne1410s said you can use promise.all() or forkjoin() to achieve that

    – Mohit Patil
    Jan 3 at 6:11

















The promises are not resolved. To write synchronous-looking code with promises, you can use async/await keywords. Alternatively use a single Promise.all(...) callback to ensure your 4 promises are resolved by array time

– ne1410s
Jan 3 at 6:01





The promises are not resolved. To write synchronous-looking code with promises, you can use async/await keywords. Alternatively use a single Promise.all(...) callback to ensure your 4 promises are resolved by array time

– ne1410s
Jan 3 at 6:01













How do I get the numeric value from that promise and assign it to the interface's variable? That's where I am confused most.

– user2325154
Jan 3 at 6:03





How do I get the numeric value from that promise and assign it to the interface's variable? That's where I am confused most.

– user2325154
Jan 3 at 6:03




1




1





everything in home.ts is ASYNC, you need to make sure that all of the promises are resolved before you start to push data inside calculations array. as @ne1410s said you can use promise.all() or forkjoin() to achieve that

– Mohit Patil
Jan 3 at 6:11





everything in home.ts is ASYNC, you need to make sure that all of the promises are resolved before you start to push data inside calculations array. as @ne1410s said you can use promise.all() or forkjoin() to achieve that

– Mohit Patil
Jan 3 at 6:11












1 Answer
1






active

oldest

votes


















3














Create a promise.all for each user crop model, with inside the list of promises of your async requests.



When you resolve the inner ones, get back a single calculation object.
When you resolve all of them, get your calculations list:



Your code should look something like:



private calculate() {
const promises: Promise<any> = ;
for (let i = 0; i < this.userCropTxModels.length; i++) {
let userCropTxModel = this.userCropTxModels[i];
promises.push(Promise.all([
this.userCropProvider.getGrossMarketableByCropId(userCropTxModel.cropId),
this.userCropProvider.getAPHMarketableByCropId(userCropTxModel.cropId),
this.userContractProvider.getTotalContractedBushelsByCropId(userCropTxModel.cropId),
this.userContractProvider.getTotalContractDollarAmountByCropId(userCropTxModel.cropId)
]).then(data => ({
cropName: 'Corn',
grossMarketable: data[0],
amountSold: data[1],
totalContractDollarAmount: data[2]
})));
}
Promise.all(promises).then(calculations => console.log(calculations));
}


EDIT



A bit of refactor. I don't know if it works, I am just coding without even trying, but just a bit cleaner:



private calculate() {
const promises: Promise<any> = this.userCropTxModels.map(userCropModel => Promise.all([
this.userCropProvider.getGrossMarketableByCropId(userCropModel.cropId),
this.userCropProvider.getAPHMarketableByCropId(userCropModel.cropId),
this.userContractProvider.getTotalContractedBushelsByCropId(userCropModel.cropId),
this.userContractProvider.getTotalContractDollarAmountByCropId(userCropModel.cropId)
]).then(data => ({
cropName: 'Corn',
grossMarketable: data[0],
amountSold: data[1],
totalContractDollarAmount: data[2]
})));
Promise.all(promises).then(calculations => console.log(calculations));
}


You can even use async/await if you want to write sync/style code






share|improve this answer


























  • Let me try this

    – user2325154
    Jan 3 at 6:09











  • All the console.log statements are getting shown in red in editor hence I commented those out. The final console.log(calculations) statement never got printed.

    – user2325154
    Jan 3 at 6:12











  • sorry the console logs should be removed, I forgot to remove them after the copy and paste

    – quirimmo
    Jan 3 at 6:12











  • there was also a typo at the last line: calculationS inside the then

    – quirimmo
    Jan 3 at 6:14











  • Perfect that worked. Thanks so much. A quick question though. In order to build the calculations array we never used the CalcModel interface? Can I use this same calculations array to display all these values on a page or do I need to typecast it to CalcModel object and then use it?

    – user2325154
    Jan 3 at 6:23












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54016961%2fnot-sure-how-to-populate-an-array-within-a-method-that-has-promises-within-it%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














Create a promise.all for each user crop model, with inside the list of promises of your async requests.



When you resolve the inner ones, get back a single calculation object.
When you resolve all of them, get your calculations list:



Your code should look something like:



private calculate() {
const promises: Promise<any> = ;
for (let i = 0; i < this.userCropTxModels.length; i++) {
let userCropTxModel = this.userCropTxModels[i];
promises.push(Promise.all([
this.userCropProvider.getGrossMarketableByCropId(userCropTxModel.cropId),
this.userCropProvider.getAPHMarketableByCropId(userCropTxModel.cropId),
this.userContractProvider.getTotalContractedBushelsByCropId(userCropTxModel.cropId),
this.userContractProvider.getTotalContractDollarAmountByCropId(userCropTxModel.cropId)
]).then(data => ({
cropName: 'Corn',
grossMarketable: data[0],
amountSold: data[1],
totalContractDollarAmount: data[2]
})));
}
Promise.all(promises).then(calculations => console.log(calculations));
}


EDIT



A bit of refactor. I don't know if it works, I am just coding without even trying, but just a bit cleaner:



private calculate() {
const promises: Promise<any> = this.userCropTxModels.map(userCropModel => Promise.all([
this.userCropProvider.getGrossMarketableByCropId(userCropModel.cropId),
this.userCropProvider.getAPHMarketableByCropId(userCropModel.cropId),
this.userContractProvider.getTotalContractedBushelsByCropId(userCropModel.cropId),
this.userContractProvider.getTotalContractDollarAmountByCropId(userCropModel.cropId)
]).then(data => ({
cropName: 'Corn',
grossMarketable: data[0],
amountSold: data[1],
totalContractDollarAmount: data[2]
})));
Promise.all(promises).then(calculations => console.log(calculations));
}


You can even use async/await if you want to write sync/style code






share|improve this answer


























  • Let me try this

    – user2325154
    Jan 3 at 6:09











  • All the console.log statements are getting shown in red in editor hence I commented those out. The final console.log(calculations) statement never got printed.

    – user2325154
    Jan 3 at 6:12











  • sorry the console logs should be removed, I forgot to remove them after the copy and paste

    – quirimmo
    Jan 3 at 6:12











  • there was also a typo at the last line: calculationS inside the then

    – quirimmo
    Jan 3 at 6:14











  • Perfect that worked. Thanks so much. A quick question though. In order to build the calculations array we never used the CalcModel interface? Can I use this same calculations array to display all these values on a page or do I need to typecast it to CalcModel object and then use it?

    – user2325154
    Jan 3 at 6:23
















3














Create a promise.all for each user crop model, with inside the list of promises of your async requests.



When you resolve the inner ones, get back a single calculation object.
When you resolve all of them, get your calculations list:



Your code should look something like:



private calculate() {
const promises: Promise<any> = ;
for (let i = 0; i < this.userCropTxModels.length; i++) {
let userCropTxModel = this.userCropTxModels[i];
promises.push(Promise.all([
this.userCropProvider.getGrossMarketableByCropId(userCropTxModel.cropId),
this.userCropProvider.getAPHMarketableByCropId(userCropTxModel.cropId),
this.userContractProvider.getTotalContractedBushelsByCropId(userCropTxModel.cropId),
this.userContractProvider.getTotalContractDollarAmountByCropId(userCropTxModel.cropId)
]).then(data => ({
cropName: 'Corn',
grossMarketable: data[0],
amountSold: data[1],
totalContractDollarAmount: data[2]
})));
}
Promise.all(promises).then(calculations => console.log(calculations));
}


EDIT



A bit of refactor. I don't know if it works, I am just coding without even trying, but just a bit cleaner:



private calculate() {
const promises: Promise<any> = this.userCropTxModels.map(userCropModel => Promise.all([
this.userCropProvider.getGrossMarketableByCropId(userCropModel.cropId),
this.userCropProvider.getAPHMarketableByCropId(userCropModel.cropId),
this.userContractProvider.getTotalContractedBushelsByCropId(userCropModel.cropId),
this.userContractProvider.getTotalContractDollarAmountByCropId(userCropModel.cropId)
]).then(data => ({
cropName: 'Corn',
grossMarketable: data[0],
amountSold: data[1],
totalContractDollarAmount: data[2]
})));
Promise.all(promises).then(calculations => console.log(calculations));
}


You can even use async/await if you want to write sync/style code






share|improve this answer


























  • Let me try this

    – user2325154
    Jan 3 at 6:09











  • All the console.log statements are getting shown in red in editor hence I commented those out. The final console.log(calculations) statement never got printed.

    – user2325154
    Jan 3 at 6:12











  • sorry the console logs should be removed, I forgot to remove them after the copy and paste

    – quirimmo
    Jan 3 at 6:12











  • there was also a typo at the last line: calculationS inside the then

    – quirimmo
    Jan 3 at 6:14











  • Perfect that worked. Thanks so much. A quick question though. In order to build the calculations array we never used the CalcModel interface? Can I use this same calculations array to display all these values on a page or do I need to typecast it to CalcModel object and then use it?

    – user2325154
    Jan 3 at 6:23














3












3








3







Create a promise.all for each user crop model, with inside the list of promises of your async requests.



When you resolve the inner ones, get back a single calculation object.
When you resolve all of them, get your calculations list:



Your code should look something like:



private calculate() {
const promises: Promise<any> = ;
for (let i = 0; i < this.userCropTxModels.length; i++) {
let userCropTxModel = this.userCropTxModels[i];
promises.push(Promise.all([
this.userCropProvider.getGrossMarketableByCropId(userCropTxModel.cropId),
this.userCropProvider.getAPHMarketableByCropId(userCropTxModel.cropId),
this.userContractProvider.getTotalContractedBushelsByCropId(userCropTxModel.cropId),
this.userContractProvider.getTotalContractDollarAmountByCropId(userCropTxModel.cropId)
]).then(data => ({
cropName: 'Corn',
grossMarketable: data[0],
amountSold: data[1],
totalContractDollarAmount: data[2]
})));
}
Promise.all(promises).then(calculations => console.log(calculations));
}


EDIT



A bit of refactor. I don't know if it works, I am just coding without even trying, but just a bit cleaner:



private calculate() {
const promises: Promise<any> = this.userCropTxModels.map(userCropModel => Promise.all([
this.userCropProvider.getGrossMarketableByCropId(userCropModel.cropId),
this.userCropProvider.getAPHMarketableByCropId(userCropModel.cropId),
this.userContractProvider.getTotalContractedBushelsByCropId(userCropModel.cropId),
this.userContractProvider.getTotalContractDollarAmountByCropId(userCropModel.cropId)
]).then(data => ({
cropName: 'Corn',
grossMarketable: data[0],
amountSold: data[1],
totalContractDollarAmount: data[2]
})));
Promise.all(promises).then(calculations => console.log(calculations));
}


You can even use async/await if you want to write sync/style code






share|improve this answer















Create a promise.all for each user crop model, with inside the list of promises of your async requests.



When you resolve the inner ones, get back a single calculation object.
When you resolve all of them, get your calculations list:



Your code should look something like:



private calculate() {
const promises: Promise<any> = ;
for (let i = 0; i < this.userCropTxModels.length; i++) {
let userCropTxModel = this.userCropTxModels[i];
promises.push(Promise.all([
this.userCropProvider.getGrossMarketableByCropId(userCropTxModel.cropId),
this.userCropProvider.getAPHMarketableByCropId(userCropTxModel.cropId),
this.userContractProvider.getTotalContractedBushelsByCropId(userCropTxModel.cropId),
this.userContractProvider.getTotalContractDollarAmountByCropId(userCropTxModel.cropId)
]).then(data => ({
cropName: 'Corn',
grossMarketable: data[0],
amountSold: data[1],
totalContractDollarAmount: data[2]
})));
}
Promise.all(promises).then(calculations => console.log(calculations));
}


EDIT



A bit of refactor. I don't know if it works, I am just coding without even trying, but just a bit cleaner:



private calculate() {
const promises: Promise<any> = this.userCropTxModels.map(userCropModel => Promise.all([
this.userCropProvider.getGrossMarketableByCropId(userCropModel.cropId),
this.userCropProvider.getAPHMarketableByCropId(userCropModel.cropId),
this.userContractProvider.getTotalContractedBushelsByCropId(userCropModel.cropId),
this.userContractProvider.getTotalContractDollarAmountByCropId(userCropModel.cropId)
]).then(data => ({
cropName: 'Corn',
grossMarketable: data[0],
amountSold: data[1],
totalContractDollarAmount: data[2]
})));
Promise.all(promises).then(calculations => console.log(calculations));
}


You can even use async/await if you want to write sync/style code







share|improve this answer














share|improve this answer



share|improve this answer








edited Jan 3 at 6:30

























answered Jan 3 at 6:03









quirimmoquirimmo

7,72811536




7,72811536













  • Let me try this

    – user2325154
    Jan 3 at 6:09











  • All the console.log statements are getting shown in red in editor hence I commented those out. The final console.log(calculations) statement never got printed.

    – user2325154
    Jan 3 at 6:12











  • sorry the console logs should be removed, I forgot to remove them after the copy and paste

    – quirimmo
    Jan 3 at 6:12











  • there was also a typo at the last line: calculationS inside the then

    – quirimmo
    Jan 3 at 6:14











  • Perfect that worked. Thanks so much. A quick question though. In order to build the calculations array we never used the CalcModel interface? Can I use this same calculations array to display all these values on a page or do I need to typecast it to CalcModel object and then use it?

    – user2325154
    Jan 3 at 6:23



















  • Let me try this

    – user2325154
    Jan 3 at 6:09











  • All the console.log statements are getting shown in red in editor hence I commented those out. The final console.log(calculations) statement never got printed.

    – user2325154
    Jan 3 at 6:12











  • sorry the console logs should be removed, I forgot to remove them after the copy and paste

    – quirimmo
    Jan 3 at 6:12











  • there was also a typo at the last line: calculationS inside the then

    – quirimmo
    Jan 3 at 6:14











  • Perfect that worked. Thanks so much. A quick question though. In order to build the calculations array we never used the CalcModel interface? Can I use this same calculations array to display all these values on a page or do I need to typecast it to CalcModel object and then use it?

    – user2325154
    Jan 3 at 6:23

















Let me try this

– user2325154
Jan 3 at 6:09





Let me try this

– user2325154
Jan 3 at 6:09













All the console.log statements are getting shown in red in editor hence I commented those out. The final console.log(calculations) statement never got printed.

– user2325154
Jan 3 at 6:12





All the console.log statements are getting shown in red in editor hence I commented those out. The final console.log(calculations) statement never got printed.

– user2325154
Jan 3 at 6:12













sorry the console logs should be removed, I forgot to remove them after the copy and paste

– quirimmo
Jan 3 at 6:12





sorry the console logs should be removed, I forgot to remove them after the copy and paste

– quirimmo
Jan 3 at 6:12













there was also a typo at the last line: calculationS inside the then

– quirimmo
Jan 3 at 6:14





there was also a typo at the last line: calculationS inside the then

– quirimmo
Jan 3 at 6:14













Perfect that worked. Thanks so much. A quick question though. In order to build the calculations array we never used the CalcModel interface? Can I use this same calculations array to display all these values on a page or do I need to typecast it to CalcModel object and then use it?

– user2325154
Jan 3 at 6:23





Perfect that worked. Thanks so much. A quick question though. In order to build the calculations array we never used the CalcModel interface? Can I use this same calculations array to display all these values on a page or do I need to typecast it to CalcModel object and then use it?

– user2325154
Jan 3 at 6:23




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54016961%2fnot-sure-how-to-populate-an-array-within-a-method-that-has-promises-within-it%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

ts Property 'filter' does not exist on type '{}'

Notepad++ export/extract a list of installed plugins