为什么我的nodejs函数总是返回null

问题描述 投票:-2回答:3

我已经定义了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。我在这里想念的是什么。

javascript node.js asynchronous callback async-await
3个回答
0
投票

为了返回值,必须使用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

0
投票

我只是忘记在函数中添加错误。

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

});
}

0
投票

回调函数应具有正确数量的参数。因此,如果您具有callback(parameter1,parameter2)],则应该收到类似function(parameter1,parameter2)

的结果。
function foo(callback) {
    **DB operation 
    callback(err, response);
}

function bar() {
    foo(function(err, response) {
       // do stuff here
    })
}
© www.soinside.com 2019 - 2024. All rights reserved.