Query in Firebase Cloud Functions: how do i get the value from asynchronous query?












1














I'm trying to get the path of a node in my Database where i have to do some stuff in. I'm trying to get this path with a query.



Here my database structure:



{
"root" {
"Sensori": LONG PATH HERE->
"M25S03": {
"latitude": 45.4986468234261,
"longitude": 9.16259765625,
"no2": 0.89,
"pm1": 4.54,
"pm10": 1.51,
"pm2_5": 1.84,
"pressione": 6.1,
"temperatura": 2.06,
"umidità": 8.92,
"voc": 9.4}
},
"Zones": {
"Areas": {
"CAP-20100": {
"ZONA-01": {},
"ZONA-02": {},
"ZONA-07": {
"geometry": {
"coordinates": [[[9.040955, 45.446847], ...A LOT OF POINTS, ...]],
"type": "Polygon"
},
"properties": {
},
"type": "Feature"
}}}}
}


When a new record like "M25S03" is inserted in the DB a triggered function start.
This function get the latitude and longitude to instantiate a point and then it has to understand in wich "polygon", stored in the table "Zones", the point is in.



Here the triggered Function:



export const onSensorCreate = functions.database
.ref('/Sensori/{sensorId}/feeds/{monthId}/{dayId}/{hourId}/{feedId}/')
.onCreate((snapshot, context) => {



const feedId: string = context.params.monthId + context.params.dayId + context.params.hourId + context.params.feedId
const sensorId = context.params.sensorId
console.log('new feed (id Feed:' + feedId + ') from' + sensorId)


const feed = snapshot.val()7)


var ref = snapshot.ref,
root = ref.root,
zoneRef = root.child('Zones'),
areas = zoneRef.child('Areas'),


var latitude = feed.latitude
var longitude = feed.longitude
var lnglat: number = [longitude, latitude]

var pathArea: database.Reference = getPathAreas(areas, lnglat)
.
.
.


and then the function getPatAreas wich has to return the Path of the database wich refer to the polygon containing the point



function getPathAreas(areas: database.Reference, lnglat: number): database.Reference {

var path: database.Reference
var point = turf.point(lnglat)

var query = areas.once('value', function (areasSnapshot) {

areasSnapshot.forEach(
function (childCapSnapshot) {

var a = childCapSnapshot.forEach(
function (childZoneSnapshot) {

const vettoreCoordinatePoligono: number = childZoneSnapshot.val().geometry.coordinates
var polygon = turf.polygon(vettoreCoordinatePoligono)

if (turf.booleanPointInPolygon(point, polygon)) {

path = childZoneSnapshot.ref
console.log("PATH AREA nell'if: " + path)

return true
}

return false
})
console.log("XXX " + path)
return a
}


)
console.log("YYY" + path)
})

console.log("ZZZ " + path)



if (path != undefined)
return path
else
return areas.root.child("UnrecorderAreas")


}



The query is asynchronous becouse is in a callback function, but i need to use path before that query is solved.
Infact by adding some control log in the code i can see that :



4:08:36.285 PM onSensorCreate Function execution took 15664 ms, finished with status: 'ok'
HERE I GOT THE RIGHT VALUE
4:08:36.194 PM onSensorCreate YYYhttps://sensesquaredb.firebaseio.com/Zones/Areas/CAP-20100/ZONA-07
I GOT THE RIGHT VALUE HERE TOO
4:08:36.194 PM onSensorCreate XXX https://sensesquaredb.firebaseio.com/Zones/Areas/CAP-20100/ZONA-07
4:08:36.194 PM onSensorCreate PATH AREA nell'if: https://sensesquaredb.firebaseio.com/Zones/Areas/CAP-20100/ZONA-07
4:08:32.182 PM onSensorCreate pathArea https://sensesquaredb.firebaseio.com/UnrecorderAreas
HERE I GOT UNDEFINED
4:08:32.181 PM onSensorCreate ZZZ undefined
4:08:20.888 PM onSensorCreate new feed (id Feed:2018M11D13H16M08S20) fromSensore4455
4:08:20.622 PM onSensorCreate Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
4:08:20.622 PM onSensorCreate Function execution started


So, how do i get this value in a non-asynchronous way?










share|improve this question





























    1














    I'm trying to get the path of a node in my Database where i have to do some stuff in. I'm trying to get this path with a query.



    Here my database structure:



    {
    "root" {
    "Sensori": LONG PATH HERE->
    "M25S03": {
    "latitude": 45.4986468234261,
    "longitude": 9.16259765625,
    "no2": 0.89,
    "pm1": 4.54,
    "pm10": 1.51,
    "pm2_5": 1.84,
    "pressione": 6.1,
    "temperatura": 2.06,
    "umidità": 8.92,
    "voc": 9.4}
    },
    "Zones": {
    "Areas": {
    "CAP-20100": {
    "ZONA-01": {},
    "ZONA-02": {},
    "ZONA-07": {
    "geometry": {
    "coordinates": [[[9.040955, 45.446847], ...A LOT OF POINTS, ...]],
    "type": "Polygon"
    },
    "properties": {
    },
    "type": "Feature"
    }}}}
    }


    When a new record like "M25S03" is inserted in the DB a triggered function start.
    This function get the latitude and longitude to instantiate a point and then it has to understand in wich "polygon", stored in the table "Zones", the point is in.



    Here the triggered Function:



    export const onSensorCreate = functions.database
    .ref('/Sensori/{sensorId}/feeds/{monthId}/{dayId}/{hourId}/{feedId}/')
    .onCreate((snapshot, context) => {



    const feedId: string = context.params.monthId + context.params.dayId + context.params.hourId + context.params.feedId
    const sensorId = context.params.sensorId
    console.log('new feed (id Feed:' + feedId + ') from' + sensorId)


    const feed = snapshot.val()7)


    var ref = snapshot.ref,
    root = ref.root,
    zoneRef = root.child('Zones'),
    areas = zoneRef.child('Areas'),


    var latitude = feed.latitude
    var longitude = feed.longitude
    var lnglat: number = [longitude, latitude]

    var pathArea: database.Reference = getPathAreas(areas, lnglat)
    .
    .
    .


    and then the function getPatAreas wich has to return the Path of the database wich refer to the polygon containing the point



    function getPathAreas(areas: database.Reference, lnglat: number): database.Reference {

    var path: database.Reference
    var point = turf.point(lnglat)

    var query = areas.once('value', function (areasSnapshot) {

    areasSnapshot.forEach(
    function (childCapSnapshot) {

    var a = childCapSnapshot.forEach(
    function (childZoneSnapshot) {

    const vettoreCoordinatePoligono: number = childZoneSnapshot.val().geometry.coordinates
    var polygon = turf.polygon(vettoreCoordinatePoligono)

    if (turf.booleanPointInPolygon(point, polygon)) {

    path = childZoneSnapshot.ref
    console.log("PATH AREA nell'if: " + path)

    return true
    }

    return false
    })
    console.log("XXX " + path)
    return a
    }


    )
    console.log("YYY" + path)
    })

    console.log("ZZZ " + path)



    if (path != undefined)
    return path
    else
    return areas.root.child("UnrecorderAreas")


    }



    The query is asynchronous becouse is in a callback function, but i need to use path before that query is solved.
    Infact by adding some control log in the code i can see that :



    4:08:36.285 PM onSensorCreate Function execution took 15664 ms, finished with status: 'ok'
    HERE I GOT THE RIGHT VALUE
    4:08:36.194 PM onSensorCreate YYYhttps://sensesquaredb.firebaseio.com/Zones/Areas/CAP-20100/ZONA-07
    I GOT THE RIGHT VALUE HERE TOO
    4:08:36.194 PM onSensorCreate XXX https://sensesquaredb.firebaseio.com/Zones/Areas/CAP-20100/ZONA-07
    4:08:36.194 PM onSensorCreate PATH AREA nell'if: https://sensesquaredb.firebaseio.com/Zones/Areas/CAP-20100/ZONA-07
    4:08:32.182 PM onSensorCreate pathArea https://sensesquaredb.firebaseio.com/UnrecorderAreas
    HERE I GOT UNDEFINED
    4:08:32.181 PM onSensorCreate ZZZ undefined
    4:08:20.888 PM onSensorCreate new feed (id Feed:2018M11D13H16M08S20) fromSensore4455
    4:08:20.622 PM onSensorCreate Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
    4:08:20.622 PM onSensorCreate Function execution started


    So, how do i get this value in a non-asynchronous way?










    share|improve this question



























      1












      1








      1







      I'm trying to get the path of a node in my Database where i have to do some stuff in. I'm trying to get this path with a query.



      Here my database structure:



      {
      "root" {
      "Sensori": LONG PATH HERE->
      "M25S03": {
      "latitude": 45.4986468234261,
      "longitude": 9.16259765625,
      "no2": 0.89,
      "pm1": 4.54,
      "pm10": 1.51,
      "pm2_5": 1.84,
      "pressione": 6.1,
      "temperatura": 2.06,
      "umidità": 8.92,
      "voc": 9.4}
      },
      "Zones": {
      "Areas": {
      "CAP-20100": {
      "ZONA-01": {},
      "ZONA-02": {},
      "ZONA-07": {
      "geometry": {
      "coordinates": [[[9.040955, 45.446847], ...A LOT OF POINTS, ...]],
      "type": "Polygon"
      },
      "properties": {
      },
      "type": "Feature"
      }}}}
      }


      When a new record like "M25S03" is inserted in the DB a triggered function start.
      This function get the latitude and longitude to instantiate a point and then it has to understand in wich "polygon", stored in the table "Zones", the point is in.



      Here the triggered Function:



      export const onSensorCreate = functions.database
      .ref('/Sensori/{sensorId}/feeds/{monthId}/{dayId}/{hourId}/{feedId}/')
      .onCreate((snapshot, context) => {



      const feedId: string = context.params.monthId + context.params.dayId + context.params.hourId + context.params.feedId
      const sensorId = context.params.sensorId
      console.log('new feed (id Feed:' + feedId + ') from' + sensorId)


      const feed = snapshot.val()7)


      var ref = snapshot.ref,
      root = ref.root,
      zoneRef = root.child('Zones'),
      areas = zoneRef.child('Areas'),


      var latitude = feed.latitude
      var longitude = feed.longitude
      var lnglat: number = [longitude, latitude]

      var pathArea: database.Reference = getPathAreas(areas, lnglat)
      .
      .
      .


      and then the function getPatAreas wich has to return the Path of the database wich refer to the polygon containing the point



      function getPathAreas(areas: database.Reference, lnglat: number): database.Reference {

      var path: database.Reference
      var point = turf.point(lnglat)

      var query = areas.once('value', function (areasSnapshot) {

      areasSnapshot.forEach(
      function (childCapSnapshot) {

      var a = childCapSnapshot.forEach(
      function (childZoneSnapshot) {

      const vettoreCoordinatePoligono: number = childZoneSnapshot.val().geometry.coordinates
      var polygon = turf.polygon(vettoreCoordinatePoligono)

      if (turf.booleanPointInPolygon(point, polygon)) {

      path = childZoneSnapshot.ref
      console.log("PATH AREA nell'if: " + path)

      return true
      }

      return false
      })
      console.log("XXX " + path)
      return a
      }


      )
      console.log("YYY" + path)
      })

      console.log("ZZZ " + path)



      if (path != undefined)
      return path
      else
      return areas.root.child("UnrecorderAreas")


      }



      The query is asynchronous becouse is in a callback function, but i need to use path before that query is solved.
      Infact by adding some control log in the code i can see that :



      4:08:36.285 PM onSensorCreate Function execution took 15664 ms, finished with status: 'ok'
      HERE I GOT THE RIGHT VALUE
      4:08:36.194 PM onSensorCreate YYYhttps://sensesquaredb.firebaseio.com/Zones/Areas/CAP-20100/ZONA-07
      I GOT THE RIGHT VALUE HERE TOO
      4:08:36.194 PM onSensorCreate XXX https://sensesquaredb.firebaseio.com/Zones/Areas/CAP-20100/ZONA-07
      4:08:36.194 PM onSensorCreate PATH AREA nell'if: https://sensesquaredb.firebaseio.com/Zones/Areas/CAP-20100/ZONA-07
      4:08:32.182 PM onSensorCreate pathArea https://sensesquaredb.firebaseio.com/UnrecorderAreas
      HERE I GOT UNDEFINED
      4:08:32.181 PM onSensorCreate ZZZ undefined
      4:08:20.888 PM onSensorCreate new feed (id Feed:2018M11D13H16M08S20) fromSensore4455
      4:08:20.622 PM onSensorCreate Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
      4:08:20.622 PM onSensorCreate Function execution started


      So, how do i get this value in a non-asynchronous way?










      share|improve this question















      I'm trying to get the path of a node in my Database where i have to do some stuff in. I'm trying to get this path with a query.



      Here my database structure:



      {
      "root" {
      "Sensori": LONG PATH HERE->
      "M25S03": {
      "latitude": 45.4986468234261,
      "longitude": 9.16259765625,
      "no2": 0.89,
      "pm1": 4.54,
      "pm10": 1.51,
      "pm2_5": 1.84,
      "pressione": 6.1,
      "temperatura": 2.06,
      "umidità": 8.92,
      "voc": 9.4}
      },
      "Zones": {
      "Areas": {
      "CAP-20100": {
      "ZONA-01": {},
      "ZONA-02": {},
      "ZONA-07": {
      "geometry": {
      "coordinates": [[[9.040955, 45.446847], ...A LOT OF POINTS, ...]],
      "type": "Polygon"
      },
      "properties": {
      },
      "type": "Feature"
      }}}}
      }


      When a new record like "M25S03" is inserted in the DB a triggered function start.
      This function get the latitude and longitude to instantiate a point and then it has to understand in wich "polygon", stored in the table "Zones", the point is in.



      Here the triggered Function:



      export const onSensorCreate = functions.database
      .ref('/Sensori/{sensorId}/feeds/{monthId}/{dayId}/{hourId}/{feedId}/')
      .onCreate((snapshot, context) => {



      const feedId: string = context.params.monthId + context.params.dayId + context.params.hourId + context.params.feedId
      const sensorId = context.params.sensorId
      console.log('new feed (id Feed:' + feedId + ') from' + sensorId)


      const feed = snapshot.val()7)


      var ref = snapshot.ref,
      root = ref.root,
      zoneRef = root.child('Zones'),
      areas = zoneRef.child('Areas'),


      var latitude = feed.latitude
      var longitude = feed.longitude
      var lnglat: number = [longitude, latitude]

      var pathArea: database.Reference = getPathAreas(areas, lnglat)
      .
      .
      .


      and then the function getPatAreas wich has to return the Path of the database wich refer to the polygon containing the point



      function getPathAreas(areas: database.Reference, lnglat: number): database.Reference {

      var path: database.Reference
      var point = turf.point(lnglat)

      var query = areas.once('value', function (areasSnapshot) {

      areasSnapshot.forEach(
      function (childCapSnapshot) {

      var a = childCapSnapshot.forEach(
      function (childZoneSnapshot) {

      const vettoreCoordinatePoligono: number = childZoneSnapshot.val().geometry.coordinates
      var polygon = turf.polygon(vettoreCoordinatePoligono)

      if (turf.booleanPointInPolygon(point, polygon)) {

      path = childZoneSnapshot.ref
      console.log("PATH AREA nell'if: " + path)

      return true
      }

      return false
      })
      console.log("XXX " + path)
      return a
      }


      )
      console.log("YYY" + path)
      })

      console.log("ZZZ " + path)



      if (path != undefined)
      return path
      else
      return areas.root.child("UnrecorderAreas")


      }



      The query is asynchronous becouse is in a callback function, but i need to use path before that query is solved.
      Infact by adding some control log in the code i can see that :



      4:08:36.285 PM onSensorCreate Function execution took 15664 ms, finished with status: 'ok'
      HERE I GOT THE RIGHT VALUE
      4:08:36.194 PM onSensorCreate YYYhttps://sensesquaredb.firebaseio.com/Zones/Areas/CAP-20100/ZONA-07
      I GOT THE RIGHT VALUE HERE TOO
      4:08:36.194 PM onSensorCreate XXX https://sensesquaredb.firebaseio.com/Zones/Areas/CAP-20100/ZONA-07
      4:08:36.194 PM onSensorCreate PATH AREA nell'if: https://sensesquaredb.firebaseio.com/Zones/Areas/CAP-20100/ZONA-07
      4:08:32.182 PM onSensorCreate pathArea https://sensesquaredb.firebaseio.com/UnrecorderAreas
      HERE I GOT UNDEFINED
      4:08:32.181 PM onSensorCreate ZZZ undefined
      4:08:20.888 PM onSensorCreate new feed (id Feed:2018M11D13H16M08S20) fromSensore4455
      4:08:20.622 PM onSensorCreate Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
      4:08:20.622 PM onSensorCreate Function execution started


      So, how do i get this value in a non-asynchronous way?







      node.js firebase firebase-realtime-database nosql google-cloud-functions






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 13 at 16:27









      Frank van Puffelen

      227k28371397




      227k28371397










      asked Nov 13 at 16:22









      Marco Tela

      62




      62





























          active

          oldest

          votes











          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%2f53285295%2fquery-in-firebase-cloud-functions-how-do-i-get-the-value-from-asynchronous-quer%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f53285295%2fquery-in-firebase-cloud-functions-how-do-i-get-the-value-from-asynchronous-quer%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

          Guess what letter conforming each word

          Port of Spain

          Run scheduled task as local user group (not BUILTIN)