繁体   English   中英

Javascript for循环等待回调

[英]Javascript for loop wait for callback

我有这个功能:

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; } if (isStarted) { break; }工作。 原因是如果它已经启动它不应该继续循环并尝试启动另一个循环。

我在NodeJS中这样做。

尝试使用递归定义

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

您也可以使用asyncnpm 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 - 使用async lib - async.foreach和object

暂无
暂无

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

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