【问题标题】:How use async/await with error reading sensor?如何将 async/await 与错误读取传感器一起使用?
【发布时间】: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


    【解决方案1】:
    const printConditions = async () => {
        let reading;
        try { 
            reading = await sensor.read(22, sensorPin).humidity;
        }
        catch(error) {
            console.log(error);
            reading = 75.0;
        }
        finally {
          console.log(`Current Humidity is: ${reading.fixed(2)}`);
        }
    }
    

    【讨论】:

      【解决方案2】:

      您是否尝试在调用异步函数时添加等待?

      const printConditions = async () => `Current Humidity is: ${await getHumidity().fixed(2)}`;
      

      【讨论】:

      • 感谢您的反馈,有没有办法只等待 getHumidity(),否则我的整个调用树都需要异步/等待?当传感器没有抛出错误时,它可以在任何地方没有异步/等待的情况下正常工作,即使它需要几秒钟才能执行。
      猜你喜欢
      • 2014-03-13
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      • 2019-04-15
      • 2014-06-19
      • 2018-01-14
      • 2018-09-12
      相关资源
      最近更新 更多