node.js中的err怎样去理解它
发布于 3 年前 作者 sunboy25 2268 次浏览 来自 问答

9 client.on(connect,function(connack){ 10 if(connack.returnCode == 0){
11 client.publish(“home/2ndfloor/201/temperature”,JSON.stringify({curre nt:25}),{qos: 1}, function(err){ 12 if(err == undefined){ 13 console.log(“publish finished”) 14 client.end() 15 } 16 else{ 17 console.log(“Publish failed”) 18 } 19 }) 20 }else{ 21 console.log(Connection faild: ${connack.returnCode}) 22 } 23 }) 24 我是个新手,我想问一下这段代码中的第12行的err是什么个什么东西,应该怎样理解它,有那位高手能指点一下?“mqtt.Client#publish(topic, message, [options], [callback]) callback - function (err), fired when the QoS handling completes, or at the next tick if QoS 0. An error occurs if client is disconnecting.” 这段的意思是不是讲这是这个mqtt的API函数返回的固定格式?

1 回复
someLib('sth', function (err) {
  // err
})

上面拿到的 error 跟下面的情况基本是可以类比的

try {
  someLib('sth');
} catch(err) {
  // err
}

前者是一个常见的约定写法。会有这个写法的原因是以前的 try/catch catch 不到异步的报错(不过现在用 async await 是可以 catch 到的)。

回到顶部