【问题标题】:node/express.js - forEach loop with request to API pushes result to array, but array remains emptynode/express.js - 请求 API 的 forEach 循环将结果推送到数组,但数组仍然为空
【发布时间】:2017-10-18 19:21:10
【问题描述】:

这是我 express.js 文件中的一个 sn-p:

function playlistTracks(req, res) {
var tracks = [];
var genres = ['hi'];

var playlistOption = {
    url: 'https://api.spotify.com/v1/users/' + req.params.user + '/playlists/'+ req.params.id + '/tracks',
    headers: { 'Authorization': 'Bearer ' + access_token },
    json: true
};

rp(playlistOption)
    .then(function (body) {
        tracks = body;
        return tracks;
    })
    .then(function (tracks) {
        getGenre(tracks);
        res.render('tracks', {
            data: tracks
        });
    })
    .catch(function (err) {
        console.log('couldnt get tracks' , err);
        throw err;
    });

function getGenre(tracks) {
    tracks.items.forEach(function(e){
        var reqGenre = {
            url: 'https://api.spotify.com/v1/artists/' + e.track.album.artists[0].id,
            json: true
        };

        rp(reqGenre)
            .then(function(body) {
                genres.push(body.genres)
            })
            .catch(function(err){
                console.log('couldnt get genres' , err);
                throw err
            });
    });

    io.emit('playlists', {genres: genres});
    console.log(genres) // <---empty 
}

}

“getGenre”函数是我最麻烦的地方。我想知道如何使用该函数更新“流派”数组。我尝试了几种解决方案,但似乎无法理解请求的异步性质。

我已经查看了this 和其他解决方案,但不知道如何将它们应用到我的代码中。

我正在使用request-promise 来获取 api 请求。

【问题讨论】:

  • 您的原始序列不会等待 getGenre 完成。要解决此问题,您可以让 getGenre 返回一个承诺,一旦所有类型都被推送,您就会履行该承诺。您需要对代码进行大量重新排序,并且可能使用 map 和 reduce 将 fetch 包装到 Promise 中。尝试谷歌搜索“承诺数组顺序”

标签: javascript node.js express asynchronous request


【解决方案1】:

getGenre 异步获取数据,所以你可以试试这样的代码:

function playlistTracks(req, res) {
  var tracks = [];

  var playlistOption = {
      url: 'https://api.spotify.com/v1/users/' + req.params.user + '/playlists/'+ req.params.id + '/tracks',
      headers: { 'Authorization': 'Bearer ' + access_token },
      json: true
  };

  rp(playlistOption)
    .then(function (body) {
        tracks = body;
        return tracks;
    })
    .then(function (tracks) {
        getGenre(tracks);    
        
        res.render('tracks', {
            data: tracks
        });
    })
    .catch(function (err) {
        console.log('couldnt get tracks' , err);
        throw err;
    });

  function getGenre(tracks) {
      var promises = tracks.items.map(function(e){
        var reqGenre = {
          url: 'https://api.spotify.com/v1/artists/' + e.track.album.artists[0].id,
          json: true
        };

        return rp(reqGenre)
          .then(function(body) {
            return body.genres
          })
          .catch(function(err){
            console.log('couldnt get genres' , err);
            throw err
          });
      });
      
      return Promise.all(promises).then(function(results) {
        var genres = ['hi'].concat(results);
        io.emit('playlists', {genres: genres});
        console.log(genres)
      });
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 2022-01-27
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多