iSukhi
iSukhi

Reputation: 31

how to make async call using request-promise in google home action

I am trying to call a API in onSync() and return payload so that I will get number of devices. Even the api is returning me the proper data I am unable to show the devices. Following is the code snippet.

app.onSync((body) => {
  // TODO: Implement SYNC response
  console.log('************** inside sync **************');
  var payload = {
    agentUserId:'123',
    devices:[]
  };
    //Calling Discove Devices API
    requestAPI('------ calling API ------') 
  .then(function(data){
    let result = JSON.parse(data);
    console.log('********** RESULT ********** '+util.inspect(result,{depth:null}));
    var count = 0;
    count = Object.keys(result.Devices).length;
    console.log('********** DEVICE COUNT ********** '+count);

    //forming payload json of devices
    for(var i in result.Devices){
        var item = result.Devices[i];
        payload.devices.push({
            "id" : item.ieee_address,
            "type" : 'action.devices.types.OUTLET',
            "traits" : ['action.devices.traits.OnOff'],
            name : {
               "defaultNames" : [item.mapped_load],
               "name" : item.mapped_load,
               "nicknames" : [item.mapped_load], 
            },
            "willReportState" : false,
            "deviceInfo" : {
                "manufacturer" : 'some manufacturer',
                "model" : 'Smart-Plug',
                "hwVersion" : '1.0',
                "swVersion" : '1.0.1',
            },
        });
    }

  }).catch(function(err){
    console.log(err);
  });

  console.log('PAYLOAD %J ',payload); <----- it is always empty
  return {
    requestId: body.requestId,
    payload: payload,
    };

});

API is returning me correct value but the payload is always empty. Please help. I am new to node.js and I dont know how to make async call.

Upvotes: 0

Views: 309

Answers (1)

Nick Felker
Nick Felker

Reputation: 11970

You're using an asynchronous call to get devices, and you'll need to make sure you don't return data before your request is complete. You return the Promise to the function, so it will wait:

app.onSync((body) => {
  return requestApi('...')
    .then(data => {
      return {
        requestId: body.requestId,
        payload: payload
      }
    })
})

Upvotes: 3

Related Questions