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

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

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

最新更新