Ade
Ade

Reputation: 373

How do I call 2 or more asynchronous methods in Actions on Google intent fulfilment V2

I had managed to call these 2 methods (geocoder.reverse, timezone.data) one after the other successfully in V1 DialogflowApp, but I am now upgrading to V2, and can't seem to get both asynchronous method calls right. Please help. I use these packages respectively

//FUNCTION CREATED TO GET TIMEZONE WITHOUT 'node-google-timezone' PACKAGE

function callTimezoneApi(lat, lon) {
    return new Promise((resolve, reject) => {
         let path = '/maps/api/timezone/json?location=' + lat +
          ',' + lon + '&timestamp=' + ts + '&key=' + googleApi;
         console.log('API Request: ' + host + path);
         // Make the HTTP request to get the weather
         http.get({
          host: host,
          path: path
         }, (res) => {
              let body = ''; // var to store the response chunks
              res.on('data', (d) => {
               body += d;
              }); // store each response chunk
              res.on('end', () => {
                   let response = JSON.parse(body);
                   let zoneHolder = response.timeZoneId;
                   let startTz = momentTz(); //used in fulfilling the Timezone
                   const localTime = startTz.tz(zoneHolder).format('LLL');
                   console.log(localTime);
                   return resolve(localTime);
              });
          res.on('error', (error) => {reject(error);});
        });
    });
}

Upvotes: 1

Views: 398

Answers (1)

Dennis Alund
Dennis Alund

Reputation: 3149

If you use Node 8 you can use async/await to untangle the nested callback structure. It will ensure that your asynchronous calls are completed before proceeding with the next call, that has dependency on another async value.

app.intent('saving_prompt', async (conv) => {
    if (conv.data.area) {
        const deviceCoordinatesStart = conv.device.location.coordinates;
        const latitudeValueStart = deviceCoordinatesStart.latitude;
        const longitudeValueStart = deviceCoordinatesStart.longitude;
        let start = moment(); //Start time in UTC, you could also use dateTime()
        let startTz = momentTz(); //used because of getting the Timezone
        const timestamp = 1402629305; // Just a dud placeholder to fulfil timezone function

        const startLocation = await new Promise((resolve, reject) => {
            geocoder.reverse({ lat: latitudeValueStart, lon: longitudeValueStart }, (err, res) => {
                if (err) {
                    console.log(err);
                    reject(err);
                } else {
                    resolve(res[0].administrativeLevels.level1long);
                }
            });
        });

        const localTime = await new Promise((resolve, reject) => {
            timezone.data(latitudeValueStart, longitudeValueStart, timestamp, (err, tz) => {
                if (err) {
                    console.log(err);
                    reject(err);
                } else {
                    var zoneHolder = tz.raw_response.timeZoneId;
                    resolve(startTz.tz(zoneHolder).format('LLL'));
                }
            });
        });

        app.ask('Your race starts by ' + localTime + 'at' + startLocation);
        conv.ask(new Suggestions('End Race'));
    } else {  //Returned if permission not granted
        conv.ask('You do not have your location on. Say "Locate me", to retrieve your location');
        conv.ask(new Suggestions(['Locate me', 'Exit']));

    }
});

Upvotes: 2

Related Questions