Error in function within object

0

module.exports = {
  post: (title, body, autor) => {
    this.title = title
    this.body = body
    this.autor = autor
  },
  search: function(search, arr , call){
    var result = arr.find(a => a.title == search)
    call(null, result)
  }
}

I have this code when I execute it tells me  "can not read property find of undefined", before I tried it out of module.exports. I've searched it in google and here and I can not find the error. thank you, thanks

    
asked by awamas 05.11.2016 в 18:39
source

1 answer

0

Clearly the problem is that arr is undefined , to correct the error you must add a verification as typeof arr == 'undefined' and consider the case or refer you to the caller and do the verification there to ensure that the method does not fail.

module.exports = {
  post: (title, body, autor) => {
    this.title = title
    this.body = body
    this.autor = autor
  },
  search: function(search, arr , call){
    // ok va a indicar si arr está definido y si arr.find es una función.
    var ok = typeof arr != 'undefined' &&
             typeof arr.find == 'function';
    var result = ok ? arr.find(a => a.title == search) : false;
    call(null, result)
  }
}

In practice, you could add a condition and tell the programmer that something is wrong.

    
answered by 05.11.2016 в 21:09