Atul
Atul

Reputation: 1590

TypeError: callback is not a function in Node.js

I am learning node.js and below is my code for the same

app.js :

const forecastService  = require('./forecast')

forecastService('New York', (error,data) => {

    if(error){
        console.log('Error in getWeatherForecast ')
    }else {
        console.log('data '+data)
    }
})

forecast.js :

const request  = require('request')

const getWeatherForecast = (city,callback) => {

    console.log('printing typeof callback ..'+typeof callback) 
    // prints function 
    console.log('printing callback ..'+callback)
    //prints actual function definition 

    const api = 'http://api.weatherstack.com/current?access_key=abcdefghijklmn'

    const weather_url = api + '&request='+city
    request({url:weather_url, json:true} , (error,response,callback) => {

        if(error){       
            callback('unable to connect to weather service',undefined)
        }else (response.body.error){
            const errMessage = 'Error in Response :'+response.body.error.info 
            console.log(errMessage)
            callback(errMessage,undefined) // getting error here 
        }
    }) 
}

module.exports = getWeatherForecast

Issue :

In forecast.js , at line callback(errMessage,undefined) , I am getting error - TypeError: callback is not a function

I have also printed callback in forecast.js as typeof callback = function and callback = actul function definition

But I am still not getting ay clue what is the error .

Can anybody please help ?

I have gone through public posts like TypeError : callback is not a function where all is saying callback is not passed correctly as a parameter which seems NOT the case with me

Upvotes: 1

Views: 2223

Answers (1)

eol
eol

Reputation: 24555

The problem is that your request-callback definition is wrong. According to the docs

The callback argument gets 3 arguments:

  • An error when applicable (usually from http.ClientRequest object)
  • An http.IncomingMessage object (Response object)
  • The third is the response body (String or Buffer, or JSON object if the json option is supplied)

So obviously the third paramter is not a function and in fact you're shadowing the callback from the outer scope. You can fix this problem by simply removing the third paramter:

request({url:weather_url, json:true} , (error,response) => {

        if(error){       
            callback('unable to connect to weather service',undefined)
        }else if (response.body.error){
            const errMessage = 'Error in Response :'+response.body.error.info 
            console.log(errMessage)
            callback(errMessage,undefined) // getting error here 
        } else {
           // handle success
           callback(undefined, response.body);
        }
}) 

A word of advice - you should use Promises and async/await instead of callbacks as it greatly increases the readability and the flow of your code.

Upvotes: 1

Related Questions