2016-11-12 64 views
0

返回一个值,我是比较新的Javascript和我真的不明白我在做什么错在这里,但返回值没有被设置:如何在Javascript

found = _dataDictionary.findOne(findByModelNameQuery, function(err, result) { 
    if (result) { 
     if (result.record) { 
      found = true 
     } else { 
      found = false 
     } 
    } 
    return found 
}); 
+5

您可能正在使用...异步回调。 – Hydro

+1

你是否在某处调用函数? – Marciano

+0

这是我正在使用的'完整'代码Model.observe('access',function(ctx,next,cb)var _dataDictionary = loopback.findModel('dataDictionary'); found = _dataDictionary.findOne(findByModelNameQuery ,功能(ERR,结果){ 如果(结果){ 如果(result.record){ 发现= TRUE }其他{ 发现= FALSE }} 回报 发现 }); ... 根据找到的值设置query.where ..... ctx.query.where = query.where } next(); }); –

回答

0

似乎_dataDictionary.findOneasynchronous function。因此,从语句返回的值与回调中稍后分配的值不同。

重构你的榜样会希望告诉你这一点:

_dataDictionary.findOne(findByModelNameQuery, function(err, result) { 
    if (result) { 
    if (result.record) { 
     found = true 
    } else { 
     found = false 
    } 
    } 

    // This statement returns to the `findOne` line executing this callback 
    // return found; 

    // Instead you can log here to see the value 
    console.log('FOUND', found); 
}); 

UPDATE:根据您的意见(以及一些更多的假设),你可以重构提供了价值返回给调用函数:

Model.observe('access', function(ctx, next, cb) { 
    var _dataDictionary = loopback.findModel('dataDictionary'); 

    _dataDictionary.findOne(findByModelNameQuery, function(err, result) { 
    if (result) { 
     if (result.record) { 
     found = true; 
     } else { 
     found = false; 
     } 
    } 

    // Assuming cb is the method to return values if async 
    cb(found); 
    }); 

    // Assuming this is for async behavior to notify to the `observe` caller that this is an async callback 
    next(); 
}); 
0

当您使用回调函数(findOne中最后一个参数中的函数)时,为了返回结果,我向您请求使用回调函数。

为了得到结果,你可以这样做:

function myFunction(myParams, callback){ 
    _dataDictionary.findOne(myParams, function(err,result){ 
     return callback(err,result); 
    }); 
} 

然后你就可以在其他地方称之为 “myFunction的”,如:

... 
myFunction(params, function(err,result){ 
     //do something with the result) 
} 

OBS1:如果PARAMS是一个又一个的功能,这样做的“丑陋”方式是使用嵌套回调,通常是“反模式”。

function myFunction(myParams, callback){ 
    _dataDictionary.findOne(myParams, function(err,result1){ 
     _anotherAsyncFunction(result1.params, function(err,result2){ 
       //do something with result2 and callback it. 
     }); 
    }); 
} 

OBS2:您可以使用库,比如async“瀑布”方法或bluebird Promise Library“然后”方法避免这种反模式。

+0

谢谢大家。得到它的工作:-) –