问题
Dear stackoverflow community,
I am using application craft as a JS cloud IDE and integrating Parse's cloud database for storage.
I'm writing a subscription service and want to check to see if a user is already subscribed prior to either authenticating their use or prompting them to sign up. Being an asynchronous call I'm trying to utilise Parse's/Promise's .then method to wait for the server's response before proceeding.
I've read the examples and samples on the Parse site (linked before) yet cannot wrap my head around it.
This code functions, and returns the email address if a match is found:
... *Parse declaration etc*
query.find({
success: function(results){
if(results.length>0){
app.setValue("lblOutput", results[0].attributes.email);
}
else{
app.setValue("lblOutput", "No match.");
}
},
error: function(object, error){
console.log(error.message);
console.log(object);
}
});
My attempt at chaining, most recently this:
query.find().then(function(results) {
if(results){
console.log("Within the Then!");
console.log(results);
}
else{
console.log("Could be an error");
}
});
States that method or property 'success' is invalid for undefined. I have attempted to combine the syntax of the first function (success: ... // error: ...) in the chaining attempt unsuccessfully.
Any advice as to how I could
- Check to see if an email exists in the Parse DB, then
- Wait until the result comes back for further manipulation with another function
would be greatly appreciated.
Once I have .then() figured out there will be further layers of async waiting.
Cheers,
James
回答1:
Your syntax for handling then is incorrect, it should be:
query.find().then(
function(results) {
console.log("Within the Then!");
console.log(results);
},
function(error){
console.log("Could be an error"+error);
}
);
the then() function takes one or two functions.
the first is a success handler, and the second is an error handler.
query.find().then(success,error)
This snippet is untested but should be pretty close.
var query = new Parse.Query(Parse.User);
query.equalTo(email, "me@me.com");
query.count().then(
function(resultsCount) {
//success handler
if(resultsCount > 0){
doSomeOtherFunction();
}
},
function(error){
//error handler
console.log("Error:"+error);
}
);
If you have more async work to do, your method should look similar to this, remember that when chaining promises the last then() should contain your error handling.
query.find().then(function(result){
doSomethingAsync(); //must return a promise for chaining to work!
}).then(function(result1){
doSomethingAsync2(); //must return a promise for chaining to work!
}).then(function(result2){
doSomethingAsync3(); //must return a promise for chaining to work!
}).then(null,function(error){
// an alternative way to handle errors
//handles errors for all chained promises.
})
来源:https://stackoverflow.com/questions/24977141/parse-then-method-and-chaining-syntax-eludes-me