[英]Azure IoT Edge node SDK invokeDeviceMethod not working asynchronously
I am trying to return a result for a direct method call in an async fashion.我试图以异步方式返回直接方法调用的结果。
I tried:我试过:
var client = Client.fromConnectionString(process.env.AZ_IOT_CONNECTION_STRING);
var methodParams = {
methodName: "method",
payload: 10, // Number of seconds.
responseTimeoutInSeconds: 60
};
// Call the direct method on your device using the defined parameters.
client.invokeDeviceMethod(
req.params.deviceId,
methodParams,
(err, result) => {
if (err) {
console.error(err);
} else {
console.log("success");
}
}
);
On Device:在设备上:
const method = async (request, response) => {
const longProcess = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 5000);
});
};
try {
await longProcess();
response.send(200, `success`);
} catch (error) {
response.send(500, `Error: ${error}:`);
}
};
client.onDeviceMethod("method", method);
Expected : Returns success after 5 seconds预期:5 秒后返回成功
Actual : returns "BadRequest" "errorCode :400027" but the method is executed correctly.实际:返回“BadRequest”“errorCode :400027”但该方法执行正确。
please work with the promise function instead of the callback like so:请使用 promise 函数而不是像这样的回调:
async deviceSyncInvoke(deviceID: string, methodName: string, data:any, responseTimeoutInSeconds?: number): Promise<[number, any]> {
try{
if (!this.client){
await this.openClient();
}
const methodParam: DeviceMethodParams = {
methodName: methodName,
payload: JSON.stringify(data)
}
// The minimum and maximum values for responseTimeoutInSeconds are 5 and 300 seconds.
//If timeout is not provided, it the default value of 30 seconds is used
if (responseTimeoutInSeconds && responseTimeoutInSeconds !== undefined) {
methodParam.responseTimeoutInSeconds = responseTimeoutInSeconds;
}
const res: ResultWithIncomingMessage<any> = await this.client.invokeDeviceMethod(deviceID, methodParam);
if (res.message.statusCode == undefined || res.message.statusCode > 299) {
throw new Error(`statusCode: ` + res.message.statusCode + `statusMessage: ` + res.message.statusMessage);
}
return [2001, "message invoking command with res: " + res];
}catch(err) {
return [5000, "error deviceSyncInvoke: " + err];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.