Scholli
Scholli

Reputation: 429

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. Many times, when there isn't an err, the items array is empty. 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...

Upvotes: 0

Views: 112

Answers (2)

vbguyny
vbguyny

Reputation: 1172

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

Upvotes: 1

user2441511
user2441511

Reputation: 11116

You should check if the array is empty before iterating with forEach. Check items.length.

There is a much longer, detailed explanation in this StackOverflow answer.

Upvotes: 1

Related Questions