我想保存一个在 Parse 云代码中随机生成的registrationId,所以我需要检查该值是否已经在数据库中,我必须以递归方式执行此操作,直到获得正确的字符串。这是我到目前为止所尝试的,问题是 findRegistrationId() 不是一个承诺,所以我不能使用 then() 有没有办法让它成为一个承诺或任何其他解决方法?对于云代码
function getRandomString()
{
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
var string_length = 4;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum + 1);
}
return randomstring;
}
function findRegistrationId()
{
console.log("Enter findRegistrationId")
var randomString = getRandomString();
var query = new Parse.Query("Book");
query.equalTo("registrationId", randomString);
query.find.then(function(results){
if(results.length === 0)
{
console.log("no registrationId duplicated")
return randomString;
}
//if there is other registrationId we concatenate
else
{
console.log("registrationId duplicated let's recursive it")
return findRegistrationId();
}
},function(error){
return error;
})
}
// Use Parse.Cloud.define to define as many cloud functions as you want.
// Gets the unique cool BC identificator. The real glue of BC!
Parse.Cloud.define("GetBookId", function(request, response) {
var promise = findRegistrationId();
promise.then(function(result){
console.log("success promise!!")
response.success(result);
}, function(error){
console.error("Promise Error: " + error.message);
response.error(error);
});
});