[英]Javascript setting variable value
我想從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);
};
提前致謝
您必須將警報(或其他任何警報)帶入異步回調:
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
});
您的函數調用是異步的。 這意味着,即使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);
});
}
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.