[英]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!");
}
}
I can't understand what it going wrong here, I've seen suggestions at AJAX calls are async (does that mean that they happen when the page is loading?) how can i tweak this to work? 我不明白这里出了什么问题,我已经看到AJAX调用中的建议是异步的(这意味着它们是在页面加载时发生的吗?)我如何调整它的工作?
In neither function do you have a return
statement. 在这两个函数中都没有return
语句。 Both of them will always return undefined
. 它们都将始终返回undefined
。
Update: You have added a return statement to only one of your functions. 更新:您仅在其中一个函数中添加了return语句。 The other will still always return undefined. 另一个仍将始终返回undefined。 That is the return value of any function that exits without execution passing through a return
statement. 那是没有执行而通过return
语句退出的任何函数的返回值。
Because you 因为你
You will need to put the logic in the callback
method of the getJSON
call. 您需要将逻辑放入getJSON
调用的callback
方法中。
Try this code, first, you must understand why this code works 尝试此代码,首先,您必须了解为什么此代码有效
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.