-
-
Save willdages/4139857 to your computer and use it in GitHub Desktop.
randomParse.rb in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var query = new Parse.Query("Classname"); | |
query.count({ | |
error: function(error) { | |
// Error counting objects | |
}, | |
success: function(count) { | |
query.skip(Math.floor(Math.random() * (count - 1))); | |
query.first({ | |
error: function(error){ | |
// Error getting object | |
}, | |
success: function(object) { | |
// Your random object | |
} | |
}); | |
} | |
}); |
Here it in in Coffeescript (untested):
query = new Parse.Query("Classname")
query.count
error: (error) ->
# Error counting objects
success: (count) ->
query.skip Math.floor(Math.random() * (count - 1))
query.first
error: (error) ->
# Error getting object
success: (object) ->
# Your random object
count
and skip
can be inefficient. Have you considered doing it this way instead?
https://parse.com/questions/is-it-possible-to-query-for-a-random-object
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This has to use 2 API calls, but is a great technique (credit to @adelevie) for getting a random object from a class with Parse.