(节点:52585)未处理的承诺拒绝警告:未处理的承诺拒绝

时间:2021-03-12 00:18:01

标签: javascript node.js promise

我有一个功能,可以使用导入的 npm 包 current-weather-data 根据位置的经纬度获取某个位置的天气。我以前从未使用过 Promise,因为我通常使用 await 和 async,但这看起来很有趣并且很好​​学...当运行下面的这段代码时,它不会呈现页面并给我错误 {{1} }--unhandled-rejections=strict(node:52585) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag

这是我的代码:

 (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2) (node:52585) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

1 个答案:

答案 0 :(得分:0)

您没有捕捉到 getWeather 函数抛出的错误。您可以向函数添加 .catch,例如

app.get('/admin-dashboard', (req, res) => {
    if (req.session.loggedin) {
      const location = {
            lat: 43.955540,
            lon: -79.480950
        }
      getWeather(location).then(weather => {
        console.log(`The temperature here is: ${weather.temperature.value}`);
        res.render('admin-dashboard', {
          page_title: "admin-dashboard",
          FN: req.session.firstname,
          LN: req.session.lastname,
          weather: weather.temperature.value,
        }).catch(err => console.log(err));
      })
    } else {
      res.render('login.ejs')
    }
})

或者如果你更舒服,你可以使用 async/await

try {
    const weather = await getWeather(location);
    console.log(`The temperature here is ${weather.temperature.value}`);

    res.render("admin-dashboard", {
        page_title: "admin-dashboard",
        FN: req.session.firstname,
        LN: req.session.lastname,
        weather: weather.temperature.value,
    });
} catch(err) {
    console.log(err);
}

请注意,我只是记录错误,您可以根据需要处理它们。