resolve() 函数在承诺中返回未定义

resolve() function is returning undefined in a promise

我正在将 youtube-dl npm 包转换为具有 promise 而不是回调,所以我有工作功能但它没有解析 resolve 功能我在这里遗漏了什么吗? 我的 youtube 下载器功能如下所示:

const fs = require('fs');
const youtubedl = require('youtube-dl');


const downloadVideoAsync = (url) => {
    const video = youtubedl(url,['--format=18'],{ cwd: __dirname }); 
     if( video !== null) {
         video.on('info', function(info) {
             console.log('Download started');
             console.log('filename: ' + info._filename);
             console.log('size: ' + info.size);
             const videoName = info.fulltitle.replace(/\s+/g, '-').toLowerCase();
             if(videoName) {

                 return new Promise((resolve, reject) =>{
                     video.pipe(fs.createWriteStream(`videos/${videoName}.mp4`));
                     video.on('end', function() {
                        console.log(`this is the videoName in async ${videoName}`);
                        resolve(true);
                     })



                 });
             }

         });
     }

}

module.exports.downloadVideoAsync = downloadVideoAsync;

我在主 server.js 文件中调用该函数,如下所示:

 const asdf = async () => {
      const result = await downloadVideoAsync('https://www.youtube.com/watch?v=EsceiAe1B6w');
      console.log(`this is the result ${result}`);
  }

  asdf();

它 returns undefined 因为那是 downloadVideoAsync 返回的内容。

  console.log(
      typeof downloadVideoAsync('https://www.youtube.com/watch?v=EsceiAe1B6w')
  ); // undefined

为了让您的代码按您希望的方式工作,您应该用 Promise 包装 video.on('info'

const downloadVideoAsync = (url) => {

    return new Promise((resolve, reject) => {

        const video = youtubedl(url,['--format=18'],{ cwd: __dirname }); 
        if(!video)
            return reject(new Error('Video is empty...'));

         video.on('error', reject);

         video.on('info', function(info) {
             console.log('Download started');
             console.log('filename: ' + info._filename);
             console.log('size: ' + info.size);
             const videoName = info.fulltitle.replace(/\s+/g, '-').toLowerCase();
             if(!videoName)
                  return reject(new Error('Empty name'));

             video.pipe(fs.createWriteStream(`videos/${videoName}.mp4`));
             video.on('end', function() {
                  console.log(`this is the videoName in async ${videoName}`);
                  resolve(true);
             });


         });

    });
}

现在,downloadVideoAsync returns 一个 Promise,而不是 undefined,它会等到 end 被调用后再解析,否则它将如果视频为空则拒绝。