2

I think the problem here might be wrong awaits, or the fact that I have a wrapped up callback inside the promise and I'm trying to resolve the promise inside that callback. Not sure how to fix this. Any help is much appreciated!

async function pointInRegion(latitude, longitude) {
  await new Promise(async (resolve, reject) => {
    try {
      const coordinate = [longitude, latitude]
      const pt = turf.point(coordinate); // tried adding await here
      fs.readFile("./regions.geojson", async function (err, data) { // tried adding await here
        if (err) throw err;
        const geojson = JSON.parse(data);
        for (const feature of geojson.features) {
          const inRegion = turf.booleanPointInPolygon(pt, feature) // tried adding await here
          if (inRegion) {
            console.log (feature.properties.name)
            return resolve(feature.properties.name)
          }
        }
      })
    } catch (err) {
      return reject(err)
    }
  })
}

I call it in the main function like:

const calculatedRegion = await pointInRegion(latitude, longitude)
console.log(calculatedRegion) // prints undefined
nickcoding2
  • 142
  • 1
  • 8
  • 34

1 Answers1

2

A couple of issues:

  1. You aren't returning your Promise to any callers
  2. You don't need async or await here, the consuming function(s) will call await on the return value of pointInRegion

Modifications with comments:

function pointInRegion(latitude, longitude) {
  // no need to await here, calling functions will await
  // return await is also not needed
  return new Promise((resolve, reject) => {
    try {
      const coordinate = [longitude, latitude]
      const pt = turf.point(coordinate);
      fs.readFile("./regions.geojson", function (err, data) { 
        if (err) {
          throw err;
        }

        const geojson = JSON.parse(data);
        for (const feature of geojson.features) {
          const inRegion = turf.booleanPointInPolygon(pt, feature);
          if (inRegion) {
            console.log (feature.properties.name);
            // no return needed for resolve
            resolve(feature.properties.name);
          }
        }
      })
    } catch (err) {
      // no return needed for reject
      reject(err);
    }
  })
}
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170