Reputation: 55263
This is how I'm doing it:
const Document = Parse.Object.extend('Document')
const query = new Parse.Query(Document)
let result = {}
query.get(id, {
success: function (object) {
result = object.toJSON()
console.log(result)
},
error: function (object, error) {
alert(`Error: ${error.code} ${error.message}`)
}
})
console.log(result)
return result
The first console.log(result)
outputs the object:
Object {content: "trstrtrts", createdAt: "2016-01-17T11:20:30.694Z", title: "Document 2", updatedAt: "2016-01-17T11:20:30.694Z", wordCount: "3000"…}
But the second one returns nothing. What's the correct way of returning an object from a Parse query?
EDIT:
Based on Anon's answer I tried this:
store.js:
store.first = (id) => {
var query = new Parse.Query(Document)
return query.get(id)
}
export default store
main.js:
store.first(to.params.id).then((document) => {
console.log(document.toJSON())
return document.toJSON()
})
But I get the following error:
Uncaught TypeError: Object function ParsePromise() { _classCallCheck(this, ParsePromise); this._resolved = false; this._rejected = false; this._resolvedCallbacks = []; this._rejectedCallbacks = []; } has no method 'all'
Upvotes: 1
Views: 228
Reputation: 2929
The second
console.log(result)
take place before the first one.Query is an async operation. The correct way of doing this is to use promises. For example you can do
function foo(id){
var Document = Parse.Object.extend('Document');
var query = new Parse.Query(Document);
return query.get(id);
}
and then use the function foo like this:
foo(objectID).then(function(object){
//do something with the object.
})
here is an example to show the async in js.
console.log('a');
setTimeOut(function(){console.log('b')},0);
console.log('c');
the order of the printing is a c b
(we have time out 0 but the function of the timeout goes in the event loop and take place after the function done)
for more information you can read https://developer.mozilla.org/he/docs/Web/JavaScript/EventLoop about the eventloop
Upvotes: 1