Javascript for循环等待回调

标签 javascript node.js for-loop asynchronous break

我有这个功能:

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 中这样做。

最佳答案

尝试使用递归定义来代替

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

关于Javascript for循环等待回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31028427/

相关文章:

javascript - 使用三个js拖拽一个obj文件

javascript - 对数据表进行排序

javascript - '{}' 类型的参数不可分配给 Angular 8 中类型的参数

javascript - 在 Node.JS 中将文本/字符串转换为图像的最佳方式

node.js - Sequelize 一对多查询(包含)产生 Y 与 X 无关

c++ - 使用稍旧版本的 GLIBCXX

swift - For-in 循环走得太远,在展开时发现 'nil'

javascript - 将 gtag 事件从跨域发送到父域

java - 将符号从 for 循环传递到 if 语句

javascript - for循环跳过间隔javascript