簡體   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