gpt4 book ai didi

javascript - 风 sails : How to return a value from the find function

转载 作者:行者123 更新时间:2023-11-30 10:00:07 27 4
gpt4 key购买 nike

我在 sails 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 */}
});

关于javascript - 风 sails : How to return a value from the find function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32139034/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com