Select to view content in your preferred language

Getting Max Value using SummaryStatistics

633
3
Jump to solution
04-11-2023 01:08 PM
TheGamer
Occasional Contributor

Hi, so I'm trying to find the maximum value for a field using summary Statistics however im getting an undefined value when trying to do console.log()

var maxVAL=0;
summaryStatistics({
  layer: fieldlayer,
  field: "fieldName",
}).then(function(stats){
  maxVAL= stats.max;
  // console.log(maxVAL) // works here
});
console.log(maxVAL)
0 Kudos
1 Solution

Accepted Solutions
TheGamer
Occasional Contributor

Hi @JamesIng I tried to use maxVAL outside the async function() and im getting promise pending

let maxVAL=0;
async function asynCall() {
const stats = await summaryStatistics({
  layer: fieldlayer,
  field: "fieldName",
});
  return Promise.resolve(stats.max);
}

maxVAL = asynCall()

 

View solution in original post

0 Kudos
3 Replies
JamesIng
Occasional Contributor

Because the summaryStatistic is async, the script will call summaryStatistic() and then immediately run the next line of code which is your bottom console.log(maxVal). 

But because the summaryStatistic hasn't actually finished yet maxVal will return 0.
The .then() only runs once summaryStatistic has finished which is why the console.log inside that function returns the correct result.

Javascript introduced async/await to help write cleaner code that is easier to read.
await means - wait for the function to return before continuing onto the next line.

Using await your code would look like:

async function() {
let maxVAL=0;
const stats = await summaryStatistics({
  layer: fieldlayer,
  field: "fieldName",
});

  maxVAL= stats.max;
  console.log(maxVAL);
}

 

James from www.landkind.com
TheGamer
Occasional Contributor

Hi @JamesIng I tried to use maxVAL outside the async function() and im getting promise pending

let maxVAL=0;
async function asynCall() {
const stats = await summaryStatistics({
  layer: fieldlayer,
  field: "fieldName",
});
  return Promise.resolve(stats.max);
}

maxVAL = asynCall()

 

0 Kudos
JamesIng
Occasional Contributor

Cool you're real close, with async/await it essentially replaces the classic Javascript promises.

In your case you should be able to tweak return stats directly from asyncCall() and await the results 

So would look like something like:

async function asynCall() {
const stats = await summaryStatistics({
  layer: fieldlayer,
  field: "fieldName",
});
  return stats.max;
}

let maxVAL = 0;
maxVal = await asynCall()

 
Another great thing to look at is in es6 you can now do whats known as 'destructuring' so you can actually reference a property of an object directly.


In your case we would tweak the above into:

async function asynCall() {
const stats = await summaryStatistics({
  layer: fieldlayer,
  field: "fieldName",
});
 return stats;
}

let { max }= await asynCall()



James from www.landkind.com
0 Kudos