0

I am getting an error while trying to return from a nested function in javascript. After the execution of let after = YD.on("finished", async function (err, done) {return done;}); I want to get the value of "done" in "after". But it is returning some other values. Can anybody help me with this please. Thank you in advance.

async function downloadVideo(videoID) {

  let YD = new YoutubeMp3Downloader({
    ffmpegPath: "/usr/local/bin/ffmpeg",
    outputPath: "./public/assets/",
    youtubeVideoQuality: "lowest",
    queueParallelism: 2,
    progressTimeout: 2000,
  });


  YD.download(videoID, `${videoID}.mp3`);

  let after = YD.on("finished", async function (err, done) {return done;});

  console.log(after);

}

downloadVideo("lTTajzrSkCw");
2
  • Callback functions in Javascript don't return values to the original scope and are executed as defined by the parent function (in this case being YD.on. Commented Jun 15, 2020 at 23:15
  • Similar question already discussed: stackoverflow.com/questions/58569495/… Commented Jun 15, 2020 at 23:19

1 Answer 1

0

Mixing callbacks, async and events can be really challenging! This solution creates a new promise that resolves on finished. Then we set after = await finished.

I was able to give this a try locally and it worked.

const YoutubeMp3Downloader = require('youtube-mp3-downloader')

async function downloadVideo (videoID) {
  const YD = new YoutubeMp3Downloader({
    ffmpegPath: '/usr/local/bin/ffmpeg',
    outputPath: './public/assets/',
    youtubeVideoQuality: 'lowest',
    queueParallelism: 2,
    progressTimeout: 2000
  })

  YD.download(videoID, `${videoID}.mp3`)

  const finished = new Promise((resolve, reject) => {
    YD.on('finished', function (err, done) {
      if (err) reject(err)
      resolve(done)
    })
  })

  const after = await finished

  console.log(after)
}

downloadVideo('lTTajzrSkCw')

Sign up to request clarification or add additional context in comments.

Comments

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.