0

I have two files: getPopular.js and getPlayListByBPM.js. I am importing function from getPopular.js to getPlayListByBPM.js.

In getPopular.js, I wrote two async functions:

var getPopularArtists = async () => {
    //https://nodejs.org/api/http.html#http_http_request_options_callback

    request.get(options, function(error, response, body) {
        return getArtistNameIdMap(body, {});
    })
}

var getPopularTracks = async () => {
    request.get(options, function(error, response, body) {
        return getTrackIdList(body, {});
    })
}

module.exports = {
    GetPopularArtists: getPopularArtists,
    GetPopularTracks: getPopularTracks,
}

with getArtistNameIdMap and getTrackIdList non-async functions.

In getPlayListByBPM.js, I import the functions like this:

const GetPopular = require('./getPopular');

var popularArtists = await GetPopular.GetPopularArtists();

var getPlaylistsByBPM = (req, res) => {
console.log(popularArtists);
res.send("This is my BPM" + req.params.BPM);
}

While it gives me:

var popularArtists = await GetPopular.GetPopularArtists();
                     ^^^^^

SyntaxError: await is only valid in async function

I would like to know how can should I call getPopularArtists function when having them imported into another JS file?

IsaIkari
  • 1,002
  • 16
  • 31
  • It has nothing to do with it being in another source file. The error message explains **exactly** what the problem is: you can only use `await` (for now) in an `async` function. Your code does not follow that rule. – Pointy Nov 26 '20 at 16:20

1 Answers1

0

The error message is trying to convey that await needs to be used inside an async-declared function.

The below is what is expected, I believe:

var getPlaylistsByBPM = async (req, res) => {
  var popularArtists = await GetPopular.GetPopularArtists();
  console.log(popularArtists);
  res.send("This is my BPM" + req.params.BPM);
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83