【发布时间】:2021-03-16 02:10:04
【问题描述】:
评论:我确信这很简单,但我似乎无法找出 async/await try/catch 的正确组合。
Senario:我正在读取可能返回错误的 DHT22 温度/湿度传感器,在这种情况下我想返回默认值。我希望 getHumidity() 等待读取并返回值或默认值。然后 printConditions() 简单调用,直到收到响应才会执行。
问题:getHumidity() 是否可能有延迟,而其他调用不知道它的异步,因为我有很多 printConditions() 变体?
const printConditions = () => `Current Humidity is: ${getHumidity().fixed(2)}`;
//Both Attempts return: Current Humidity is NaN%
//Which I believe implies it is not waiting nor default value of 75.0.
//Attempt 1
const getHumidity = async () => {
try { return await sensor.read(22, sensorPin).humidity; }
catch (error) {console.log(error); return 75.0; }
}
try/catch 块返回此错误:??? : (node:1368) UnhandledPromiseRejectionWarning: 未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。 (拒绝编号:1)
//Attempt 2:
const getHumidity = async () => {
return await sensor.read(22, sensorPin)
.then(value=>{ return value.humidity;})
.catch(error=>{console.log(error); return 75.0;});
}
【问题讨论】:
标签: javascript node.js express async-await raspberry-pi