Merlin W.
Merlin W.

Reputation: 3

Node.js returning an API response within an async function

I have written the following code to retrieve song lyrics from the apiseeds lyric api.

const apiseeds = require("apiseeds-lyrics");
const apiseedskey = "MY_API_KEY";

async function getLyrics(artistName, songName)
{
    return await apiseeds.getLyric(apiseedskey, artistname, songName, 
    (response) => {
        return response;
    });
}


var artist = "Darius Rucker";
var title = "Wagon Wheel";
var lyrics = await getLyrics(artist, title)
console.log(lyrics);

I should also mention that the second block of code there is enclosed within an eventEmitter.on event with an asynchronous callback function.

Whenever the code runs, I get undefined in the console.

Upvotes: 0

Views: 318

Answers (1)

Victor Nascimento
Victor Nascimento

Reputation: 781

async and await can only be used to treat asynchronous functions that returns Promises, not callbacks. You should be able to transform your call to use Promises, or use another library.

The main reason we use await is to wait for the promise to resolve before continuing the code execution:

const result = await codeThatReturnsPromise()
console.log(result)

We could transform your code to this:

// async here means it returns a promise
async function getLyrics(artistName, songName)
{
  return new Promise((resolve, reject) => {
    apiseeds.getLyric(apiseedskey, artistname, songName, (response) => resolve(response))
  })
}

var artist = "Darius Rucker";
var title = "Wagon Wheel";
var lyrics = await getLyrics(artist, title)
console.log(lyrics);

Upvotes: 1

Related Questions