0

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.

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Would you happen to know how I can transform my call to return a Promise?
Yes, you can use new Promise((resolve, reject) => ... resolve(value)), so you call the resolve callback with the data provenient from your callback function.
Added to answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.