Javascript设置变量值

问题描述:

我想从if if else block中设置stat的值,但是当我设置它并提醒它时,它对我说“undefined”。我如何设置统计值。这是我的代码。Javascript设置变量值

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); 
}; 

由于提前

你必须把警报(或其他)到异步回调:

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); 
    }); 
} 

当你调用API,它会立即返回。因此,如果您有外部警报,则立即调用它。然后,稍后,调用您的回调函数(您作为第三个参数传递的函数)。

编辑:你不能从deleteComment返回stat。相反,这样做:

deleteComment = function(postId, callback){ 
    FB.api(postId, 'delete', function(response) { 
    if (!response || response.error) { 
     stat = "Error2"; 
    } else { 
     stat = "Deleted" 
    } 
    callback(stat); 
    }); 
} 

你可以称之为一样:

deleteComment(postid, function(stat) 
{ 
    // use stat 
}); 
+0

基本上我想返回从删除评论的统计值 – Novice 2010-09-09 18:34:09

你的函数调用asynchronuous。这意味着,您的代码中的alert()在HTTP请求尚未返回时运行。

不要在回调函数的警报,因为只有这样,它有一个值:

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); 
    }); 
} 

Facebook的API是asynchronous,这意味着你传递给FP.api来电会后的回调函数,API时通话已结束,但在拨打FB.api后,您的提醒将立即运行,这当然意味着回叫功能尚未运行,因此stat仍为Don't Know

要使其工作,你必须把alert回调中:

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 
}