[英]Javascript check if array filled from function
I have this function 我有这个功能
offer.getReceivedItems(function(err, items) {
It returns an array (items) or throws an error err
if it failed. 它返回一个数组(项目),或者如果失败则抛出错误
err
。 Many times, when there isn't an err
, the items array is empty. 很多时候,当没有
err
,items数组为空。 Like 喜欢
[]
But when this array is empty, I need to try the same function again 但是当此数组为空时,我需要再次尝试相同的功能
offer.getReceivedItems(function(err, items) {
but how I can go back to it, when items is empty... 但是当物品为空时,我该如何返回到它...
I tried so much, but I cannot find it... 我做了很多尝试,但是找不到...
Code looks like 代码看起来像
offer.getReceivedItems(function(err, items) {
if (err) {
console.log("Couldn't get received items: " + err);
offer.decline();
} else {
console.log(items);
items.forEach(function(item,i,arr){
....
The forEach
doesn't run when there is an empty array... 当有一个空数组时,
forEach
不会运行。
You should check if the array is empty before iterating with forEach
. 在使用
forEach
迭代之前,应检查数组是否为空。 Check items.length
. 检查
items.length
。
There is a much longer, detailed explanation in this StackOverflow answer . 这个StackOverflow答案中有更长,更详细的解释。
I am having trouble understanding what it is you are trying to do but does the following help you? 我无法理解您要做什么,但是以下内容对您有帮助吗?
var callBack = function(err, items) {
if (err) {
console.log("Couldn't get received items: " + err);
offer.decline();
offer.getReceivedItems(callBack); // Call again
} else {
console.log(items);
items.forEach(function(item,i,arr){
....
}
};
// Original call
offer.getReceivedItems(callBack);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.