简体   繁体   中英

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

I have a web app that uses JavaScript, jQuery, and async.times (among other components) to get a list of artists and songs from the Spotify API and insert them into the page in order. On my local Node.js server, this functionality works perfectly. However, upon deploying to Heroku, there seems to be an error involving the asynchronous function, because it seems to run the loop twice and append the list two times.

This is the code that appends the data to the page:

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

The deployed version is here: http://whatshouldilistentotoday.herokuapp.com/finalproject/

Heroku says that it shouldn't be a problem on their end, because they use a vanilla Node.js installation on ubuntu, but I can't figure out why async.times would run the proper number of times locally but not on their server.

You are creating properties on an object in the loop that deletes all properties from that object.

This is begging for trouble. From 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.

So just don't do that, it's completely implementation-dependent. I wouldn't be surprised if this goes into an infinite loop and hangs your server.

Just use two separate objects, for your own sanity. Apart from that, I don't see any reason to use these integer counter properties at all, just go for async.forEachOfSeries instead of that .times method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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