2012-01-06 47 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); 
     }); 

    } 
相关问题