Javascript设置变量值

时间:2010-09-09 17:57:40

标签: javascript facebook fbjs

我想从if else块设置stat的值但是当我设置它并提醒它时它会告诉我“undefined”。如何设置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);
};

先谢谢

3 个答案:

答案 0 :(得分: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
});

答案 1 :(得分:1)

您的函数调用是异步的。这意味着,当HTTP请求尚未返回时,代码中的alert()将运行。

在回调函数中执行警报,因为只有它具有值:

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

答案 2 :(得分:1)

Facebook API为asynchronous,这意味着当API调用完成后,您传递给FP.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
}