我已经定义了2个函数,并从另一个函数中调用了一个函数。结果始终为null
var abc = (req,callBack) => {
DB Operation
.
.
.
.
console.log(result);
callBack(null,result);
}
var def = (req, callBack) => {
abc(req,(response) => {
callBack(null,result);
});
}
console.log打印实际结果,但来自函数def的callBack始终返回null。我在这里想念的是什么。
为了返回值,必须使用return
关键字。 console.log
不是返回值。例如:
function nonReturningFunction(){
console.log('foo')
}
function returningFunction(){
console.log('bar')
return 'baz'
}
console.log('Output of non-returning function: '+nonReturningFunction())
// foo will print, but function returns 'undefined'
console.log('Output of returning function: '+ returningFunction())
// 'bar' will print, but only 'baz' will be in the function return
我只是忘记在函数中添加错误。
var abc = (req,callBack) => {
DB Operation
.
.
.
.
console.log(result);
callBack(null,result);
}
var def = (req, callBack) => {
abc(req,(err, response) => {
if(err){
callBack({
error:'Oops Something went wrong'
});
}else{
callBack(null,result);
}
});
}
您回调函数应具有正确数量的参数。因此,如果您具有callback(parameter1,parameter2)],则应该收到类似function(parameter1,parameter2)
的结果。function foo(callback) {
**DB operation
callback(err, response);
}
function bar() {
foo(function(err, response) {
// do stuff here
})
}