简体   繁体   中英

Break out of a “for” loop within a callback function, in Node.js

Regarding the code below, my goal is to break out of FOR LOOP B and continue with FOR LOOP A, but within a callback function.

for(var a of arrA) {
    // ...
    // ...

    for(var b of arrB) {
        // ...
        // ...

        PartService.getPart(a.id, function(err, returnObj) {
            break;
        });
    }
}

Will this give me the results I want? If not, how can I achieve this?


EDIT 4/28/16 3:28 MST

  • The callback function is indeed asynchronous

Based on one of the answers and all the comments below, without changing the scope of the question, perhaps the best question at this point is "How do I implement a synchronous callback function in Node.js?". I am considering refactoring my code so to remove for loops, but I am still curious if I can still go in this direction using synchronous callback functions. I know that Underscore.js uses synchronous callback functions, but I do not know how to implement them.

You can try something like this, however it will work only when the callback is fired synchronously.

for(var a of arrA) {
  let shouldBreak = false;
  for(var b of arrB) {
    if (shouldBreak)
      break;
   // rest of code
     PartService.getPart(a.id, function(err, returnObj) { // when the callback is called immediately it will work, if it's called later, it's unlikely to work
       shouldBreak = true;
    });

This might not give you expected result . You can use events EventEmitter or async module .

You can also try having it loop by itself without a for loop. Making it asynchronous.

for (var a of arrA) {
    var _loop = function(i) {

        // Make modifications to arrB
        
        PartService.getPart(id, function(err, retObj) {
            if (err) {
                throw err;
            }

            if (retObj.success) {
                // If successful, call function again
                _loop(i + 1);
            } else {
                // We've broken out of the loop
            }
        });
    };
    // Instantiate loop
    _loop(0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM