简体   繁体   English

在 Node.js 中的回调函数中跳出“for”循环

[英]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 LOOP B 并继续 FOR LOOP A,但在回调函数内。

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编辑 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?".根据以下答案之一和所有评论,在不改变问题范围的情况下,此时最好的问题可能是“如何在 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.我正在考虑重构我的代码以删除 for 循环,但我仍然很好奇我是否仍然可以使用同步回调函数朝这个方向发展。 I know that Underscore.js uses synchronous callback functions, but I do not know how to implement them.我知道 Underscore.js 使用同步回调函数,但我不知道如何实现它们。

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 .您可以使用事件EventEmitterasync模块。

You can also try having it loop by itself without a for loop.您也可以尝试让它在没有for循环的情况下自行循环。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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