风帆:如何从查找function返回一个值

我在js工作。 我想返回variablessequence[0].NextValue 但我没有得到它。

 function AutoGenerate(tablename) { Sequence.find({TableName:tablename}).exec(function(err,sequence){ if(err) { console.log("err"); return res.negotiate(err); } else { console.log(sequence); var intCurrentNo = sequence[0].NextValue; var intNextNo = sequence[0].NextValue + sequence[0].IncrementBy; if (intNextNo < sequence[0].MinimumValue || intNextNo > sequence[0].MaximumValue) { console.log("Error While Updating UserId") return res.badRequest('Next value not between the Minimum and Maximum value'); } else { sequence[0].NextValue = intNextNo; console.log(intNextNo); sequence[0].save(function(err) { if (err) { console.log("error while update"); return res.negotiate(err); } else { console.log("Incremented"); console.log(sequence[0].NextValue); return sequence[0].NextValue; } }); } } }); } 

但是Sequence.find({TableName:tablename})函数没有返回任何值。 请帮我摆脱这个。

你不能返回一个值,因为它是一个asynchronous方法,你必须使用callback来完成:

 function AutoGenerate(tablename, callback) { Sequence.find({TableName : tablename}).exec(function (err, sequence) { if (err) { console.log("err"); callback(err); } else { console.log(sequence); var intCurrentNo = sequence[0].NextValue; var intNextNo = sequence[0].NextValue + sequence[0].IncrementBy; if (intNextNo < sequence[0].MinimumValue || intNextNo > sequence[0].MaximumValue) { console.log("Error While Updating UserId") callback(new Error('Next value not between the Minimum and Maximum value')); } else { sequence[0].NextValue = intNextNo; console.log(intNextNo); sequence[0].save(function (err) { if (err) { console.log("error while update"); callback(err); } else { console.log("Incremented"); console.log(sequence[0].NextValue); callback(null, sequence[0].NextValue); } }); } } }); } 

并像这样调用它:

 AutoGenerate("myTableName", function(err, nextValue){ if(err){res.negotiate(err);} else {/* DO WHAT YOU WANT */} });