如何在Google Home Action中使用请求承诺进行异步调用

时间:2018-10-15 14:50:59

标签: actions-on-google google-home google-smart-home

我试图在onSync()中调用一个API并返回有效负载,这样我就可以得到许多设备。甚至api也向我返回了无法显示设备的正确数据。以下是代码段。

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向我返回了正确的值,但是有效载荷始终为空。 请帮忙。我是node.js的新手,我不知道如何进行异步调用。

1 个答案:

答案 0 :(得分:3)

您正在使用异步调用来获取设备,并且需要确保在请求完成之前不返回数据。您将Promise返回到该函数,因此它将等待:

CARS.ID