我正在处理这个API,我需要这个函数来返回一个responseObject,但是这个值需要在返回之前由异步侦听器设置。问题是节点js在侦听器有机会修改该值的值之前立即返回它们。
除了一会儿(responseObject === undefined)循环之外我还能做什么来防止函数立即返回?
注意:我还没有写过其他的switch语句。
exports.queryServer = function (useIPv6, databaseId, apiId, ipAddress, serverIp, timeoutDelay, port) {
var client = useIPv6 ? dgram.createSocket("udp6") : dgram.createSocket("udp4");
var transactionId = randomstring.generate({
length: 20,
charset: "alphanumeric"
});
var queryString = databaseId + ";" + apiId + ";" + ipAddress + ";" + implementationProtocolVersion + ";" + nodeJSAPI + ";" + transactionId + ";";
var responseObject;
client.on("error", function (err) {
responseObject = "Socket error : " + err;
});
client.send(queryString, 0, queryString.length, port, serverIp, function () {
console.log("Querying Server : " + queryString);
});
var timeoutObject = setTimeout(function () {
client.close();
//alert user/throw error here
console.log("Error : Request timed out after " + timeoutDelay + " milliseconds");
responseObject = "Error : Response timed out after " + timeoutDelay + " milliseconds";
}, timeoutDelay);
client.on("message", function (message) {
client.close();
clearTimeout(timeoutObject);
var msg = message.toString();
var responseArray = msg.split(";;")[1].split(";");
switch(databaseId){
case 12:
responseObject = new na_proxy(responseArray);
break;
}
console.log("Server Response : " + msg);
});
return responseObject;
}