Async.times 将 Node.js 应用程序部署到 heroku 时出错(重复循环)

Async.times error when deploying Node.js app to heroku (repeated loop)

我有一个使用 JavaScript、jQuery 和 async.times(以及其他组件)从 Spotify API 并将它们按顺序插入到页面中。在我的本地 Node.js 服务器上,此功能完美运行。然而,在部署到 Heroku 时,似乎有一个涉及异步函数的错误,因为它似乎 运行 循环两次并附加列表两次。

这是将数据附加到页面的代码:

var counter = 0;
      for (var id in relatedArtists) {
        relatedArtists[counter] = relatedArtists[id];
        delete relatedArtists[id];
        counter++;
      }
async.times(counter, function(n, next) {
  console.log(n);
  console.log(relatedArtists[n].id);
  s.getArtistTopTracks(relatedArtists[n].id, "US", function (err, data2) {
    relatedArtists[n].song = data2.tracks[0].name; 
    relatedArtists[n].uri = data2.tracks[0].uri;
    $('#related-artist').append(
      '<p><strong>' + relatedArtists[n].name + '</strong> -- \"' +
      relatedArtists[n].song + '\"</p>'
    );
    next(null, relatedArtists[n].uri);       
  });
}, 

部署的版本在这里:http://whatshouldilistentotoday.herokuapp.com/finalproject/

Heroku 说这对他们来说应该不是问题,因为他们在 ubuntu 上使用 vanilla Node.js 安装,但我不明白为什么 async.times会 运行 在本地而不是在他们的服务器上的正确次数。

您正在循环中的某个对象上创建属性,该循环会删除该对象的所有属性。

这是找麻烦。来自 the spec:

If new properties are added to the target object during enumeration, the newly added properties are not guaranteed to be processed in the active enumeration.

所以不要那样做,它完全取决于实现。如果这进入无限循环并挂起您的服务器,我不会感到惊讶。

为了您自己的理智,只需使用两个单独的对象。除此之外,我看不出有任何理由使用这些整数 counter 属性,只需使用 async.forEachOfSeries 而不是 .times 方法。