Issue
Hi I need to calculate the average of a promise called every 1 second during 3 seconds
Without success I have tried this:
return new Promise(resolve=>{
var c = { x : 0 , y : 0};
var list = [1,2,3];
const task = async () => {
for (const item of list) {
await new Promise(r => setTimeout(getGeoLoc, 1000));
console.log('Yello, D\'oh');
}
let l = list.length
c.x = c.x / l;
c.y = c.y /l;
}
return resolve(c)
function getGeoLoc(){
return this.coords.then(resp=>{
c.x = c.x + resp.x;
c.y = c.y + resp.y
return
})}
})
Solution
Without seeing a minimal, reproducible example of your code, here's something that should help you compute the average coordinates that you seem to want to find:
function wait (delayMs: number): Promise<void> {
return new Promise(res => setTimeout(res, delayMs));
}
function getRandomInt (min = 0, max = 1): number {
return Math.floor(Math.random() * (max + 1 - min)) + min;
}
type Coords = Record<'x' | 'y', number>;
// this is a mock for whatever "this.coords" is
async function getCoords (): Promise<Coords> {
const x = getRandomInt(0, 100);
const y = getRandomInt(0, 100);
return {x, y};
}
function avgCoordsReducer (
avg: Coords,
{x, y}: Coords,
index: number,
{length}: Coords[],
): Coords {
avg.x += x;
avg.y += y;
if (index === length - 1) {
avg.x /= length;
avg.y /= length;
}
return avg;
}
async function main () {
const coordsPromises: Promise<Coords>[] = [];
for (let i = 0; i < 3; i += 1) {
await wait(1000);
coordsPromises.push(getCoords());
}
const averageCoords = (await Promise.all(coordsPromises)).reduce(avgCoordsReducer);
console.log(averageCoords);
}
main();
Answered By - jsejcksn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.