我正在学习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.js
,在线callback(errMessage,undefined)
,我遇到了错误-TypeError: callback is not a function
我也已在Forecast.js中将callback打印为typeof callback = function和callback = actul function定义
但我仍然不知道这是什么错误。
有人可以帮忙吗?
我已经经历过像TypeError这样的公开帖子:callback不是一个函数,所有人都在说回调没有作为参数正确传递,这对我来说似乎不是这种情况
问题是您的请求回调定义错误。根据文档
callback参数获得3个参数:
- 适用时发生错误(通常来自http.ClientRequest对象)
- http.IncomingMessage对象(Response对象)
- 第三个是响应主体(字符串或缓冲区,或者提供json选项的JSON对象)
因此,很明显,第三个参数不是函数,实际上,您正在屏蔽外部作用域中的回调。您可以通过简单地删除第三个参数来解决此问题:
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和async / await而不是回调,因为它会大大提高代码的可读性和流程。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句