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)
Solved! Go to Solution.
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()
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);
}
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()
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()