【发布时间】:2020-02-05 08:36:05
【问题描述】:
我手动成功地通过端口2345 远程登录到linux345。
这意味着以下代码应将输出显示为0
但是,代码输出返回1。
似乎将callback 转换为async promise 格式将有助于解决问题。
请建议更新后的代码是什么样的。
const net = require('net');
const HOST = 'linux345';
const PORT = 2345;
let ErrCode = 1;
const client = new net.Socket();
client.connect(PORT, HOST, function() {
ErrCode = 0;
});
client.on('data', function(data) {
console.log('Client received: ' + data);
if (data.toString().endsWith('exit')) {
client.destroy();
}
});
client.on('close', function() {
});
client.on('error', function(err) {
ErrCode = err.code;
console.log(ErrCode);
});
console.log(ErrCode);
【问题讨论】:
-
或者...您可以将最后一个
console.log()移动到有意义的回调函数中 -
我需要在代码的其他地方使用
ErrCode的值。因此,可能需要将其转换为async promise格式 -
转换什么,究竟是什么?您有四个异步事件处理程序,其中一个 (data) 连续触发。您认为“将
callback转换为async promise格式” 会在这里做什么? -
我能看到的唯一适合你的模式是 async generator 包装
data事件回调
标签: javascript node.js promise async-await angular-promise