简体   繁体   中英

Why am I getting the error “UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined”?

I have an index.js, gettext.js and extract.js.

index.js

app.post("/anaData", async function(req, res) {
  const someData = await docExtract(req.body['file_name'])
  const data = await getData(someData)
  .....
 ....
}

gettext.js

async function docExtract (file_name) {
  return new Promise(resolve => {
     var file_params = {
       Document: {
         S3Object: {
           Bucket: bucket_name,
           Name: filename
         }
       },
       FeatureTypes: ['TABLES'],
     }
     
     textract.analyzeDocument(file_params, (err, data) => {
       if (err) {
         return resolve(err)
       } else {
         resolve(data)
       }
     })
   })
 }
 module.exports = docExtract

extract.js

async function getData(data) {
    const blocks = data['Blocks']
  
    const blocksMap = {}
    const tableBlocks = []
  
    blocks.forEach(block => {  //At this point the error is generated: TypeError: Cannot read property 'forEach' of undefined"
      blocksMap[block['Id']] = block
  ....
....
}
  module.exports = getData

I am sending the right json data. I have checked that req.body['file_name'] is accessible. The problem seems to be related to the fact that the docExtract function return a promise but I just can't seem to understand what do I do. Any help would be greatly appreciated.

The error message reads:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined
    at extract (path\to\getData.js:75:12)
    at path\to\index.js:28:22
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

Cannot read property 'forEach'...

The error is saying it's trying to read a property forEach . That means this expression:

blocks.forEach

...of undefined

...which means that blocks is undefined. That means when you assign the value:

const blocks = data['Blocks']

... data['Blocks'] has the value undefined .

Because getData is an async function , it returns a Promise . If the function throws an error, and it does (trying to read forEach property of an undefined value), the promise becomes a rejection. "UnhandledPromiseRejectionWarning" means that the caller of getData is not handling these rejections. If you wrap the await in a try/catch , you can catch any error that getData throws and do something useful with it, like sending an HTTP error response.

So hopefully this explains what the error '“UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined”' means.

So to avoid the error:

  1. To avoid unhandled rejections, make sure when you call getData() or any other async function you await the result and catch errors. If you do not, then any errors, expected or unexpected, will be unhandled.
  2. To avoid reading properties of undefined values, make sure the data you're accessing is actually in the format you're expecting. In this case, it looks like data['Blocks'] is undefined, so you're either not getting the data you're expecting or you're accessing it incorrectly. Try logging data to see what you're actually getting. By the way, data.Blocks is equivalent and less typing than data['Blocks'] .

I'm not a js expert but in my experience, UnhandledPromiseRejectionWarning in this case with await occur because await is the short version of promise handling, but only the resolve part.

ie If some exceptions are thrown inside the promise function or if the promise reject s, then await is not handling that.

My educated guess is that textract.analyzeDocument() 's callback (err, data) => {} part is simply rejecting it.

It was a very silly mistake that was leading to the error. The bucket_name variable was getting substituted from an environment variable and the variable name in gettext.js and environment file were different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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