Synchronous forEach loop (wait for it to complete)

I have a function in Node.js that takes an array and passes through it, doing some laborious calculations for each element.

Here's a super-simplified version of the function:

var analyze_data = function (data) {
    data.forEach(function (elm) {
        if (elm.myProp == true) {
            return true;
        }
    });
    return false;
}

Essentially, I want the function to return true if any property of the property myPropis true. If none of the elements satisfies this condition, the function should return false.

However, the code never waits for the forEach loop to complete. In other words, if the 100th element in the array satisfies the condition, the function should return true. Instead, it goes to return false;and returns false until the loop ends forEach.

Is there a solution for this?

Edit

, , - Node.js es6-, :

var analyze_data = function (data) {
    return new Promise(function (resolve, reject) {
        data.forEach(function (elm) {
            if (elm.myProp == true) {
                resolve(elm);
            }
        });
        resolve(false);
    });
}

, forEach, . , , , true, false. , , false, , .

?: p !

+4
3

/ . , , true ( analyze_data), false .

Array.prototype.some:

var analyze_data = function (data) {
    return data.some(function (elm) {
        return elm.myProp == true;
    });
}
+5

, forEach , . , , .

true .

forEach forEach, , . :

. forEach. Array.every Array.some.

+4

, true, . , :

var retVal = false;
data.forEach(function (elm) {
    if (elm.myProp == true) {
        retVal = true;
    }
});
return retVal;

:

var analyze_data = ***function (data)*** {
  data.forEach(***function (elm)*** {
    if (elm.myProp == true) {
        return true; //returns out of function(elm)
    }
  });
  //the true value is gone - you didn't do anything with it
  return false; //always returns false out of function(data)
}

EDIT:

data.forEach(function (elm) {
    if (elm.myProp == true) {
        resolve(elm);
    }
});
resolve(false);

() elm, false. 100% , , . , :

is_found = false;
data.forEach(function (elm) {
    if (elm.myProp == true) {
        resolve(elm);
        is_found = true;
    }
});
if (!is_found) {
    resolve(false);
}

, , :

if (!is_found) {
   reject(false);
}

, :

promise.then(function(result) {
    // do stuff since it found stuff :)
}, function(err) {
    // do stuff since if didn't find anything :(
});
+1

All Articles