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");
  • 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`. – m_callens Jun 15 '20 at 23:15
  • Similar question already discussed: https://stackoverflow.com/questions/58569495/how-to-return-from-nested-function-in-node-js – Ruhul Amin Jun 15 '20 at 23:19

1 Answers1

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')

Flet
  • 439
  • 2
  • 2