繁体   English   中英

为什么我的函数返回“ undefined”而不是布尔值

[英]Why is my function returning “undefined” instead of boolean

        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调用中的建议是异步的(这意味着它们是在页面加载时发生的吗?)我如何调整它的工作?

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

更新:您仅在其中一个函数中添加了return语句。 另一个仍将始终返回undefined。 那是没有执行而通过return语句退出的任何函数的返回值。

因为你

  1. 不要从你的方法中返回任何东西
  2. 即使您尝试返回,由于您正在执行的异步调用( AJAX )在函数返回其值之后完成,因此您将无法返回ajax调用结果...

您需要将逻辑放入getJSON调用的callback方法中。

尝试此代码,首先,您必须了解为什么此代码有效

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);
      });

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM