在 node.js 程序中,我正在努力使用 async/await http get 函数,以获取 domotica 设备 zigbee 网关的状态。 该脚本不会等到 http get 服务完成。经过一些努力,我无法等待。 这是代码。
async function PlugWiseGetStatusbyName(pAuthorbase64, pApplianceName) {
let lStatusCode = '' ;
let lReplyBody = '' ;
let lLen = 0 ;
let lPosBegin = 0;
let lPosEind = 0;
let GetURL = "http://"+STRETCH_IP+"/core/appliances;name="+pApplianceName ;
let GetBody = "" ;
console.log('GetURL = '+GetURL+'\n Body = '+GetBody) ;
let getRequest = {
host: STRETCH_IP,
path: GetURL,
port: 80,
method: "GET",
headers: {
'Host': STRETCH_IP,
//'Connection': 'Close',
'Content-Type': 'application/xml',
// 'Content-Length': Buffer.byteLength(body),
'Authorization': 'Basic '+ pAuthorbase64
}
};
let buffer = "";
let req = await http.request( getRequest, await function( res ) {
lStatusCode = res.statusCode ;
lReplyBody = res.responseText ;
console.log('req Statuscode: ' + lStatusCode );
// let buffer = "";
res.on( "data", function( data ) {
buffer = buffer + data;
} );
res.on( "end", function( data ) {
console.log( 'on end ') ; // +buffer );
lLen = buffer.length ;
lPosBegin= buffer.indexOf('<state>') ;
lPosEind = buffer.indexOf('</state>') ;
console.log('posities zijn '+lPosBegin.toString(10)+', '+lPosEind.toString(10) );
PWSwitchStatus = buffer.substring(lPosBegin+7, lPosEind) ;
if (PWSwitchStatus != "on" && PWSwitchStatus != "off") {
PWSwitchStatus = "onbekend" ;
}
console.log(' substring PWSwitchStatus = '+PWSwitchStatus) ;
} ); // of res.end
});
await req.on('error', function(e) {
console.log('problem with request: ' + e.message);
PWSwitchStatus = 'error' ;
});
// req.write( GetBody );
req.end();
console.log('buffer = '+buffer) ;
console.log('reply Body = '+lReplyBody) ;
console.log('net for return PWSwitchStatus = '+PWSwitchStatus) ;
return PWSwitchStatus ;
} // end function PlugWiseGetStatusbyName
console.log('starting http get REST ..') ;
var status = "empty";
status = PlugWiseGetStatusbyName(AUTHORBASE64, ApplianceName) ;
console.log('Get Status= '+status) ;
console.log('PW SwitchStatus = '+PWSwitchStatus) ;
console.log("done....")
解决这个问题的最佳方法是什么。
提前致谢。
我在各种网络文章中学习了async/await的概念,但这些主要是简单的例子。
您的代码存在一些问题,导致它不等待 HTTP 请求完成:
传给http.request的回调函数没有定义为async。因此,在函数内部使用 await 是没有效果的。要解决此问题,您可以将回调函数单独定义为异步函数并将其引用传递给 http.request。
await关键字用在传给http.request的回调函数之前。由于此函数不返回承诺,因此在此处使用 await 无效。相反,您可以使用 Promise 构造函数创建一个承诺,该承诺在 HTTP 响应完成时解析,并将 await 与此承诺一起使用。
这是您应该可以使用的代码的更新版本:
const http = require('http');
async function PlugWiseGetStatusbyName(pAuthorbase64, pApplianceName) {
let lStatusCode = '';
let lReplyBody = '';
let lLen = 0;
let lPosBegin = 0;
let lPosEind = 0;
let GetURL = 'http://' + STRETCH_IP + '/core/appliances;name=' + pApplianceName;
let GetBody = '';
console.log('GetURL = ' + GetURL + '\n Body = ' + GetBody);
let getRequest = {
host: STRETCH_IP,
path: GetURL,
port: 80,
method: 'GET',
headers: {
'Host': STRETCH_IP,
//'Connection': 'Close',
'Content-Type': 'application/xml',
// 'Content-Length': Buffer.byteLength(body),
'Authorization': 'Basic ' + pAuthorbase64,
},
};
let buffer = '';
let req = http.request(getRequest, async function (res) {
lStatusCode = res.statusCode;
lReplyBody = res.responseText;
console.log('req Statuscode: ' + lStatusCode);
// let buffer = "";
res.on('data', function (data) {
buffer = buffer + data;
});
res.on('end', function (data) {
console.log('on end '); // +buffer );
lLen = buffer.length;
lPosBegin = buffer.indexOf('<state>');
lPosEind = buffer.indexOf('</state>');
console.log('posities zijn ' + lPosBegin.toString(10) + ', ' + lPosEind.toString(10));
PWSwitchStatus = buffer.substring(lPosBegin + 7, lPosEind);
if (PWSwitchStatus != 'on' && PWSwitchStatus != 'off') {
PWSwitchStatus = 'onbekend';
}
console.log(' substring PWSwitchStatus = ' + PWSwitchStatus);
}); // of res.end
});
req.on('error', function (e) {
console.log('problem with request: ' + e.message);
PWSwitchStatus = 'error';
});
req.end();
await new Promise((resolve) => {
req.on('close', () => resolve());
});
console.log('buffer = ' + buffer);
console.log('reply Body = ' + lReplyBody);
console.log('net for return PWSwitchStatus = ' + PWSwitchStatus);
return PWSwitchStatus;
} // end function PlugWiseGetStatusbyName
console.log('starting http get REST ..');
var status = 'empty';
PlugWiseGetStatusbyName(AUTHORBASE64, ApplianceName).then((result) => {
status =