Javascript setting variable value
I want to set the value of stat from if else block but when I set it and alert it then it says to me "undefined". How can I set the value of stat. Here is my code.
deleteComment = function(postId){
var stat = "Don't Know";
FB.api(postId, 'delete', function(response) {
if (!response || response.error) {
stat = "Error2";
} else 开发者_如何转开发{
stat = "Deleted"
}
});
alert(stat);
};
Thanks in Advance
Your function call is asynchronuous. This means, the alert()
in your code runs when the HTTP request has not even returned yet.
Do the alert in the callback function, because only then it has a value:
deleteComment = function(postId){
FB.api(postId, 'delete', function(response) {
var stat = "Don't Know";
if (!response || response.error) {
stat = "Error2";
} else {
stat = "Deleted";
}
alert(stat);
});
}
The Facebook API is asynchronous, that means the callback function you pass to the FP.api
call will later, when the API call has finished, but your alert will run immediately after you made the call to FB.api
which of course means that the callback function did not yet run and therefore stat is still Don't Know
.
To make it work, you have to put the alert
inside your callback:
deleteComment = function(postId){
var stat = "Don't Know";
// call is made...
FB.api(postId, 'delete', function(response) {
// if we land here, the callback has been called
if (!response || response.error) {
stat = "Error2";
} else {
stat = "Deleted"
}
alert(stat); // now - inside the callback - stat is actually set to the new value
});
// but execution continues
}
You have to bring the alert (or whatever) into the async callback:
deleteComment = function(postId){
var stat = "Don't Know";
FB.api(postId, 'delete', function(response) {
if (!response || response.error) {
stat = "Error2";
} else {
stat = "Deleted"
}
alert(stat);
});
}
When you call the API, it returns immediately. Thus, if you have the alert outside, it is called immediately. Then, later, your callback (the function you pass as the third parameter) is called.
EDIT: You can't return stat
from deleteComment. Instead, do:
deleteComment = function(postId, callback){
FB.api(postId, 'delete', function(response) {
if (!response || response.error) {
stat = "Error2";
} else {
stat = "Deleted"
}
callback(stat);
});
}
You could call this like:
deleteComment(postid, function(stat)
{
// use stat
});
精彩评论