1 回答
TA贡献1869条经验 获得超4个赞
脚本中有一些错误:
async
不打电话await
是没有用的通常使用回调来代替
await
,不能同时使用通用回调接口是
callback(error, data)
,所以你应该遵循这个模式
所以你的脚本应该更新如下。
请注意,这是一个无法管理错误的快速解决方案!(又名error
事件)
const status = require('net')
const util = require('util')
const hosts = [
['Server #1', 'google.com', 80],
['Server #2', 'jhfg87ed4.com', 80], // fake, just for response check
['Server #3', 'stackoverflow.com', 80]
]
function server (id, cb) {
const host = hosts[id]
const sock = new status.Socket()
sock.setTimeout(2500)
sock
.on('connect', () => {
cb(null, host[0] + ': Up.') // null as first parameter that is error
sock.destroy()
})
.on('error', e => {
cb(new Error(host[0] + ': Down: ' + e.message))
})
.on('timeout', e => {
cb(new Error(host[0] + ' Down: timeout'))
})
.connect(host[2], host[1])
}
const serverPromise = util.promisify(server)
async function results () {
let res = await serverPromise(0)
console.log(res)
try {
res = await serverPromise(1)
console.log(res)
} catch (error) {
console.log(error)
}
res = await serverPromise(2)
console.log(res)
}
results()
添加回答
举报