简体   繁体   English

NodeJS - 如何处理 UnhandledPromiseRejectionWarning?

[英]NodeJS - How to deal with UnhandledPromiseRejectionWarning?

I am fairly new to Node JS and so I am struggling a bit.我对 Node JS 还很陌生,所以我有点挣扎。

I am trying to read files for google drive using their API, from my Node Js code.我正在尝试使用他们的 API 从我的 Node Js 代码读取 google drive 的文件。

I am having the following code我有以下代码

router.get('/', function (req, res, next) {

  var pageToken = null;
// Using the NPM module 'async'
async.doWhilst(function (callback) {
  drive.files.list({
    q: "mimeType='image/jpeg'",
    fields: 'nextPageToken, files(id, name)',
    spaces: 'drive',
    pageToken: pageToken
  }, function (err, res) {
    if (err) {
      // Handle error
      console.error(err);
      callback(err)
    } else {
      res.files.forEach(function (file) {
        console.log('Found file: ', file.name, file.id);
      });
      pageToken = res.nextPageToken;
      callback();
    }
  });
}, function () {
  return !!pageToken;
}, function (err) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    // All pages fetched
  }
})

  res.render('index', { title: 'Express' });

});

The above code is giving me the following error when i send the get request当我发送获取请求时,上面的代码给了我以下错误

(node:13884) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined
    at E:\nodejs\newcelebapi\routes\index.js:49:17
    at E:\nodejs\newcelebapi\node_modules\googleapis-common\build\src\apirequest.js:43:53
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13884) 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 `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13884) [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.

The issue is in the following line问题在下一行

  res.files.forEach(function (file) {

I've tried everything I could and gave up understanding the problem.我已经尽我所能并放弃了对问题的理解。

Could you please help me with this?你能帮我解决这个问题吗?

Thanks!谢谢!

Per this example in the doc , you want to be using:根据文档中的这个示例,您希望使用:

res.data.files.forEach(...)

not:不是:

res.files.forEach(...)

And, it looks like as soon as you get by that problem, you will have another problem because you are calling res.render() in the wrong place.而且,看起来一旦你解决了这个问题,你就会遇到另一个问题,因为你在错误的地方调用res.render() And, when you fix that, you will have an issue with redefining res in your Google callback which will hide the higher level res that you need for res.render() .而且,当你解决这个问题时,你会遇到在你的谷歌回调中重新定义res的问题,这将隐藏res.render()所需的更高级别的res

I would strongly recommend that you not use the async library here.我强烈建议您不要在这里使用async库。 It doesn't seem like it's needed here and it just complicates things.这里似乎不需要它,它只会使事情复杂化。 And, if you did need help doing coordination of asynchronous operations, promises is the modern way to do so.而且,如果您确实需要帮助协调异步操作,promises 是这样做的现代方式。

You don't show what you're trying to do with the resulting files (other than logging them), but here's a simple implementation that does that:您没有显示您要对结果文件做什么(除了记录它们),但这里有一个简单的实现:

router.get('/', function (req, res, next) {
  var pageToken = null;
  drive.files.list({
    q: "mimeType='image/jpeg'",
    fields: 'nextPageToken, files(id, name)',
    spaces: 'drive',
    pageToken: pageToken
  }).then(response => {
      let files = response.data.files;
      files.forEach(file => console.log('Found file: ', file.name, file.id))
      res.render('index', { title: 'Express' });
  }).catch(err => {
      console.log(err);
      res.sendStatus(500);
  });
});

Note, that I named the parameter from drive.files.list() to be named response instead of res so I can access both res from the router.get() callback and response from the drive.files.list() callback.请注意,我指定的参数从drive.files.list()被命名response ,而不是res ,所以我可以访问两个resrouter.get()回调responsedrive.files.list()回调。 You gave them both the same name res which means you can't access the router.get() parameter of the same name.您为它们提供了相同的名称res ,这意味着您无法访问router.get()参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM