Why does my callback say: "undefined is not a function?

I call the function with a callback as follows:

$(function() { //get all the items search.init('.result tbody tr'); search.parseresults(function(announcementID){ //query every single page var myCompany = new company(announcementID); myCompany.requestPage(function(){ //on response parse the data. myCompany.parsedata() var myPerson = new person(myCompany ) myPerson.getPhone(function(){ console.log('test') }); }) }); }); 

This is the last callback with console.log ('test'), which is the problem.

this is the getPhone function:

 person.prototype.getPhone = function(callback){ this.attempt++ if( this.attempt === 1){ var who = this.lastname; var where = this.adress+' '+this.postal; }else if(this.attempt === 2){ var who = this.firstname+' '+this.lastname; var where = this.adress+' '+this.postal; }else{ var who = this.firstname+' '+this.lastname; var where = this.adress+' '+this.postal; var url = 'http://personer.eniro.se/resultat/'+who+'/'+where; console.debug('') //console.debug('fail') console.debug(url) console.debug(this) return } var self = this; var url = 'http://personer.eniro.se/resultat/'+who+'/'+where; GM_xmlhttpRequest({ method: "GET", url: url, onload: function(data) { data = $.parseHTML(data.response); var vCard = $(data).find('.vcard') if (vCard.length === 1){ var phone = vCard.find('.tel.row a').map(function(){ return this.text }).get() self.officePhone = phone[0]; if(phone.length > 1){ self.mobilePhone = phone[1]; }else{ self.mobilePhone = ''; } callback(); } else if(vCard.length > 1){ self.getPhone() } } }) } 

The callback starts when it should. But when the callback is present, I get an error message:

undefined is not a function

+6
source share
2 answers
 else if(vCard.length > 1){ self.getPhone() } 

When you make the next attempt, you are not passing a callback and then undefined in that call. One should always check if the callback is a function before the call.

 if (vCard.length === 1){ var phone = vCard.find('.tel.row a').map(function(){ return this.text }).get() self.officePhone = phone[0]; if(phone.length > 1){ self.mobilePhone = phone[1]; }else{ self.mobilePhone = ''; } // also pass some reasonable result: if (typeof callback=="function") callback(phone); } else if(vCard.length > 1) { self.getPhone(callback) } 
+9
source

Not sure if this is a problem, but this is the original idea:

In your last line, you have self.getPhone() where you do not go through the callback. So, if you achieve this code: callback(); in getPhone method, callback can be undefined.

Try:

 if (typeof(callback) === 'function') { callback() } 
+6
source

Source: https://habr.com/ru/post/951393/


All Articles