【问题标题】:TypeError: callback is not a function in Node.jsTypeError:回调不是 Node.js 中的函数
【发布时间】:2020-06-09 15:23:53
【问题描述】:

我正在学习 node.js,下面是我的相同代码

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

问题:

forecast.jscallback(errMessage,undefined) 行,我收到错误 - TypeError: callback is not a function

我还在 Forecast.js 中将回调打印为 typeof callback = function 和 callback = actul function definition

但我仍然不知道错误是什么。

有人可以帮忙吗?

我浏览过像TypeError : callback is not a function 这样的公开帖子,所有人都说回调没有作为参数正确传递,这对我来说似乎不是这样

【问题讨论】:

    标签: node.js callback


    【解决方案1】:

    问题是您的请求回调定义是错误的。根据docs

    回调参数有 3 个参数:

    • 适用时出现错误(通常来自 http.ClientRequest 对象)
    • 一个 http.IncomingMessage 对象(响应对象)
    • 第三个是 响应正文(字符串或缓冲区,或 JSON 对象,如果 json 选项是 提供)

    所以很明显第三个参数不是一个函数,实际上你是shadowing 来自外部范围的回调。您只需删除第三个参数即可解决此问题:

    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);
            }
    }) 
    

    忠告 - 您应该使用 Promises and async/await 而不是回调,因为它大大提高了代码的可读性和流动性。

    【讨论】:

      猜你喜欢
      • 2014-01-31
      • 2018-01-22
      • 2018-06-05
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 2016-06-16
      • 2017-03-28
      相关资源
      最近更新 更多