KelevraZero
KelevraZero

Reputation: 39

PARSE : Get object id after save

Iam sure it's pretty easy but I a new in javascript... I have search for a long time but I didn't find the solution In PARSE, I want to create an object and get the id went it save

var Obj = Parse.Object.extend("obj");
var obj = new Obj();
obj.save(null,{success:function(obj){alert(obj.id)}})

this alert the id but when i try to get the value I only get an undefined

var Obj = Parse.Object.extend("obj");
var obj = new Obj();
var objid;
obj.save(null,{success:function(obj){objid = obj.id}})
alert(objid)

undefined

Can you help me? Thanks

Upvotes: 0

Views: 1537

Answers (3)

tyforcode
tyforcode

Reputation: 1767

As another note, Parse at the moment includes Promises where functions can be called and defined one after another after finishing. Here's an example which returns the objectId of a newly created object.

var ParseObj = Parse.Object.extend("obj"); 
// Create a new instance of class.
var obj = new ParseObj();
obj.save(null, { useMasterKey: true }).then(function(obj) {
    response.success(obj.id);   //obj.id is the objectId
}, function(error) {
// If there's an error storing the request, render the error page.
    response.error('Failed to save object.');
});

Upvotes: 0

jeffdill2
jeffdill2

Reputation: 4114

To expand on what user2943490 correctly pointed out, if you wanted that alert() to work, simply move it into the success callback.

Upvotes: 1

user2943490
user2943490

Reputation: 6940

The success callback you pass into obj.save is called asynchronously: it executes at some point after the success response is received by the Parse library. The alert in your second example is called synchronously: it doesn't wait for the success callback to have executed, so objid will never be defined at this point.

This isn't a problem specifically related to Parse, but one of handling asynchronous code in JavaScript in general. These answers will give you a quick intro to asynchronicity in JS:

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

How do I return the response from an asynchronous call?

Upvotes: 3

Related Questions