Javascript设置变量值
我想从 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);
};
提前致谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的函数调用是异步的。这意味着,代码中的
alert()
在 HTTP 请求尚未返回时运行。在回调函数中执行警报,因为只有这样它才有值:
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:
Facebook API 是异步,这意味着您传递给
FP 的回调函数。 api
调用稍后会在 API 调用完成后进行,但您的警报将在您调用FB.api
后立即运行,这当然意味着回调函数尚未运行因此 stat 仍然是不知道
。要使其正常工作,您必须将
alert
放入回调中: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 toFB.api
which of course means that the callback function did not yet run and therefore stat is stillDon't Know
.To make it work, you have to put the
alert
inside your callback:您必须将警报(或其他内容)带入异步回调中:
当您调用 API 时,它会立即返回。因此,如果您在外面收到警报,系统会立即呼叫。然后,稍后,您的回调(作为第三个参数传递的函数)被调用。
编辑:您无法从deleteComment返回
stat
。相反,做:你可以这样称呼它:
You have to bring the alert (or whatever) into the async callback:
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:You could call this like: