我在风帆js工作。我想返回变量sequence[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})
函数不返回任何值。请帮我把这个去掉
你不能返回一个值因为这是一个异步方法你必须通过回调来完成它:
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 */}
});