1

I need help friends! I need to write function for get request in my REST API. In this function I need to get all playlists by branchId, and get for each playlist files by playlistId, and send array of objects with properties [{playlist, files}, {playlist, files}, {playlist, files}].

I think my function need to be async. I try it, but I have some problems when I want to get files for each playlist.

exports.findBranchePlaylists = async  function(req, res) {
    let data = [];
    let playlists = await Playlist.find({branch_id: req.params.branchId});
    playlists.forEach(async (playlist) => {
        let files = await File.find({playlistId: playlist._id });
        data.push({playlist, files});
    })
    res.send(playlists);
};

I know that it is wrong code, I want to show you, what I want to do. this code send me only this - [].

Smbat Poghosyan
  • 719
  • 7
  • 20
  • 1
    forEach does not supports async/await syntax. Place your code inside a FOR loop and it should work as intended. – Max Svidlo Jul 21 '19 at 12:15

2 Answers2

1

The thing with your code is that forEach loop does not suppports await syntax (as forEach is NOT async). You can change the forEach to be a classic FOR loop. Me personally I would do it like this (so 1 call will give me the data for all the ids):

exports.findBranchePlaylists = async function(req, res) { let data = []; let playlists = await Playlist.find({branch_id: req.params.branchId}); let files = await File.find({'playlistId': {$in: playlists.map( ele => ele._id) }); res.send(files); };

Max Svidlo
  • 684
  • 5
  • 11
0

It doesn't need to be async, you can make use of promise or callback function

exports.findBranchePlaylists = function(req, res) {
Playlist.find({branch_id: req.params.branchId})
        .then(result => {
    return result.map(plylist => {
         File.find({playlistId: playlist._id })
              .then(result => { return {playlist, result} })
    })
}).then( result => res.send(result))
};

or you can use for loop with async/await as forEach is not supported with async/await.

Nameless
  • 503
  • 3
  • 21