2012-01-06 46 views
0
 function checkDatabase(){ 
      var query = document.getElementById("input").value; 
      var modQuery = query.split("@")[1]; 
      var url = "http://www.somesite.com/index.html/?id="+modQuery; 

      $.getJSON(url, function(data) { 
       $.each(data, function(i, item) { 
        console.log(item); 
        if(item.length < 1){ 
         return false; 
        } else { 
         searchResult = { 
          'name':item[0].screen_name, 
          'loc':item[0].location, 
          'tweet':item[0].tweets[0].tweet_text 
         }; 
         return true; 
        } 
       }); 
      }); 
     } 

     function searchForUser(){ 
      var result = checkDatabase(); 
      console.log(result); 
      if(result){ 
       console.log(searchResult);   
      } else { 
       input.setCustomValidity("Sorry it seems you haven't tweeted about every1speaks yet!"); 
      } 
     } 

我不明白它會錯在這裏,我已經看到了在AJAX調用的建議是異步(這是否意味着它們發生時,頁面加載?)我如何調整這個工作?爲什麼我的函數返回「不確定」,而不是布爾

+0

哪裏是在'checkDatabase'(=無返回值)'return'聲明?異步請求的回調方法在哪裏? (=沒有預期的回報值)。 – 2012-01-06 11:50:43

+0

AJAX調用異步意味着它們在正常代碼流之外運行。通常,你的代碼從上到下運行,如果你調用一個函數,代碼不會繼續運行,直到函數完成。但AJAX調用只是暫時停止你的代碼,他們不會等待AJAX​​調用加載。代碼繼續,然後當AJAX調用完成時,它會運行您傳遞給它的函數。 – 2012-01-06 11:51:49

回答

2

因爲你

  1. 不會從你的方法
  2. 即使你試圖返回,因爲你正在做一個異步調用(AJAX),它的功能之後,結束返回其返回值什麼,你將無法返回Ajax調用結果...

你需要把邏輯的getJSON通話callback方法。

+0

好吧,更有意義,歡呼 – 2012-01-06 11:51:49

2

在這兩個函數中都沒有return聲明。他們兩人將永遠返回undefined

更新:你已經添加了一個返回語句只有你的一個函數。另一個將始終返回undefined。這是任何通過return聲明退出而沒有執行的函數的返回值。

+0

對不起,這是一個錯誤,我會編輯它...我得到了與return語句相同的問題。 – 2012-01-06 11:50:31

0

試試這個問題,首先,你必須明白爲什麼這個代碼工作

check_if_offer_exist_in_shopping_cart(offer_id, custumer_shopping_cart) { 

    let x = false 
    custumer_shopping_cart.forEach(element => { 
     if(offer_id === element){ 
     this.mediator.openDynamicSnackBar('This offer already exist in shopping cart','info','ok'); 
     x = true; 
     console.log(offer_id); 
     return x; 
     } 
    }); 

    return x; 

    } 


// Check if the user has this offer in his shopping cart already 
    const check = this.check_if_offer_exist_in_shopping_cart(offer_id, custumer_shopping_cart); 
    console.log('RESULT => ', check); 

    if(check){ 
     this.mediator.openDynamicSnackBar('item already exist in your shopping cart','success','ok'); 
    } else { 

     this.api_customer.add_offer_to_shopping_cart({'id' : offer_id}).subscribe(snap => { 
     console.log(snap); 
     this.mediator.openDynamicSnackBar('item added to your shopping cart','success','ok'); 
     }, error => { 
     console.log(error); 
     }); 

    } 
相關問題