0

我想从 if else 块中设置 stat 的值,但是当我设置它并警告它时,它对我说“未定义”。如何设置 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);
};

提前致谢

4

3 回答 3

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 时,它会立即返回。因此,如果您在外面有警报,它会立即被调用。然后,稍后,您的回调(作为第三个参数传递的函数)被调用。

编辑:您不能stat从 deleteComment 返回。相反,请执行以下操作:

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
});
于 2010-09-09T18:00:44.760 回答
1

您的函数调用是异步的。这意味着,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);
  });
}
于 2010-09-09T18:01:05.537 回答
1

Facebook API 是异步的,这意味着您传递给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
}
于 2010-09-09T18:03:37.060 回答