【问题标题】:Javascript for loop wait for callbackJavascript for循环等待回调
【发布时间】:2015-09-10 18:23:06
【问题描述】:

我有这个功能:

function tryStartLocalTrendsFetch(woeid) {
    var userIds = Object.keys(twitClientsMap);
    var isStarted = false;

    for (var i = 0; i < userIds.length; i++) {
        var userId = userIds[i];
        var twitClientData = twitClientsMap[userId];
        var isWoeidMatch = (woeid === twitClientData.woeid);
        if (isWoeidMatch) {

            startLocalTrendsFetch(woeid, twitClientData, function (err, data) {
                if (err) {
                    // Couldn't start local trends fetch for userId: and woeid:
                    isStarted = false;
                } else {
                    isStarted = true;
                }
            });
            // This will not obviously work because startLocalTrendsFetch method is async and will execute immediately
            if (isStarted) {
                break;
            }
        }
    }
    console.log("No users are fetching woeid: " + woeid);
}

这种方法的要点是我希望if (isStarted) { break; } 行工作。原因是如果它已经启动,它不应该继续循环并尝试启动另一个循环。

我在 NodeJS 中这样做。

【问题讨论】:

  • 尝试在 NPM 上查找 async 节点包。
  • 我将 i 在循环内设为索引变量,并将外部“for”循环更改为 while(!isStarted && i
  • 如果您要重构代码以避免回调,@Scimonster 所说的 async 将起作用。我推荐 Promises,bluebird 很棒。我最强烈的建议是使用 Kefir 的 FRP。

标签: javascript node.js for-loop asynchronous break


【解决方案1】:

尝试使用递归定义来代替

function tryStartLocalTrendsFetch(woeid) {
  var userIds = Object.keys(twitClientsMap);
  recursiveDefinition (userIds, woeid);
}

function recursiveDefinition (userIds, woeid, userIndex)
  var userId = userIds[userIndex = userIndex || 0];
  var twitClientData = twitClientsMap[userId];
  var isWoeidMatch = (woeid === twitClientData.woeid);
  if (isWoeidMatch && userIndex<userIds.length) {
      startLocalTrendsFetch(woeid, twitClientData, function (err, data) {
          if (err) {
            recursiveDefinition(userIds, woeid, userIndex + 1)
          } else {
            console.log("No users are fetching woeid: " + woeid);
          }
      });
  } else {
    console.log("No users are fetching woeid: " + woeid);
  }
}

【讨论】:

  • 啊,聪明,我在想递归方法可以在这里完成工作:)
【解决方案2】:

您也可以使用async (npm install async):

var async = require('async');

async.forEach(row, function(col, callback){
    // Do your magic here
    callback();  // indicates the end of loop - exit out of loop
    }, function(err){
        if(err) throw err;
    });

更多资料帮助你:Node.js - Using the async lib - async.foreach with object

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 2023-01-20
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多