为什么我的函数返回“undefined”而不是boolean

时间:2012-01-06 11:47:55

标签: javascript

        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调用的建议是异步的(这是否意味着它们会在页面加载时发生?)我怎样才能调整它的工作?

3 个答案:

答案 0 :(得分:2)

在这两个函数中都没有return语句。它们都将始终返回undefined

更新:您只为一个功能添加了一个return语句。另一个仍将始终返回undefined。这是在没有执行的情况下通过return语句退出的任何函数的返回值。

答案 1 :(得分:2)

因为你

  1. 不退还任何方法
  2. 即使您尝试返回,因为您正在执行异步调用( AJAX ),该函数在函数返回其值后完成,您将无法返回ajax调用结果...
  3. 您需要将逻辑放在callback来电的getJSON方法中。

答案 2 :(得分: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);
      });

    }
相关问题