我是 Parse 的新手,并试图同时围绕承诺来思考。我想做的只是在数据库中创建一个用户(如果不存在(,如果确实存在,我会更新该行。我遇到的问题是我的 Parse.Query 从未找到用户行,然后当它找不到该行时,它将无法创建新用户,因为该行存在。我知道这是因为我需要强制该方法等待搜索返回或在查询返回时返回要执行的承诺,但我无法弄清楚该怎么做。
我当前的代码是:
Parse.Cloud.define("findUser2", async req => {
var phoneNumber = req.params.phoneNumber;
phoneNumber = phoneNumber.replace(/D/g, '');
console.log("Incoming phone number is: " + phoneNumber)
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo('username', phoneNumber);
var user = await userQuery.first();
if(user) {
console.log("Found a user, user is: " + user);
//Validation stuff goes here
} else {
console.log("Did not find a user, create and return it");
var newUser = new Parse.User();
newUser.setUsername(phoneNumber);
newUser.setPassword(secretPasswordToken + phoneNumber);
newUser.set("language", "en");
newUser.setACL({});
newUser.save();
//If this is not commented out, fails with:
//Error: Cannot create a pointer to an unsaved ParseObject
//user = newUser;
}
console.log("about to return the user");
return user;
});
然后,输出返回:
app[web.1]: Incoming phone number is: 5555551212
app[web.1]: Did not find a user, create and return it
app[web.1]: about to return the user
app[web.1]: info: Ran cloud function findUser2 for user undefined with:
app[web.1]: Input: {"phoneNumber":"5555551212"}
app[web.1]: Result: undefined {"functionName":"findUser2","params":{"phoneNumber":"5555551212"}}
app[web.1]: error: Parse error: Account already exists for this username. {"code":202,"stack":"Error: Account already exists for this username.n at /app/node_modules/parse-server/lib/RestWrite.js:567:13n at processTicksAndRejections (internal/process/task_queues.js:85:5)"}
app[web.1]: (node:23) UnhandledPromiseRejectionWarning: Error: Account already exists for this username.
根据日志的顺序,我知道它在完成查询之前正在退出函数。我以为await
会强制它在此查询返回或超时之前不继续,从而能够实现承诺。看来我错了,我不确定如何解决问题。
理想情况下,我会使用 Promises,因为我可以让我的代码更有效地运行,但我现在一直在等待,因为我希望它能让它更容易工作并且适合原型。我正在寻找一条好的前进道路,如果正确的方法是回报承诺,我想知道。
您的云代码函数在实际保存新用户之前返回。您只需要在返回之前await
它。它会是这样的:
Parse.Cloud.define("findUser2", async req => {
var phoneNumber = req.params.phoneNumber;
phoneNumber = phoneNumber.replace(/D/g, '');
console.log("Incoming phone number is: " + phoneNumber)
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo('username', phoneNumber);
var user = await userQuery.first({ useMasterKey: true });
if(user) {
console.log("Found a user, user is: " + user);
//Validation stuff goes here
} else {
console.log("Did not find a user, create and return it");
var newUser = new Parse.User();
newUser.setUsername(phoneNumber);
newUser.setPassword(secretPasswordToken + phoneNumber);
newUser.set("language", "en");
newUser.setACL({});
await newUser.save(); //This is the line you need to change
//If this is not commented out, fails with:
//Error: Cannot create a pointer to an unsaved ParseObject
//user = newUser;
}
console.log("about to return the user");
return user;
});