2010-09-09 143 views
0

我想從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); 
}; 

由於提前

回答

1

你必須把警報(或其他)到異步回調:

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

1

你的函數調用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); 
    }); 
} 
1

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 
}