resolve()函数在promise中返回undefined

时间:2018-12-23 16:39:31

标签: node.js express promise youtube-dl

我正在将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;

我正在这样在main.js文件中调用该函数:

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

  asdf();

1 个答案:

答案 0 :(得分:2)

它返回undefined,因为这就是downloadVideoAsync返回的结果。

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

为使代码按您希望的方式工作,应在video.on('info'的后面加上Promise。

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返回一个Promise,而不是undefined,它将等待直到调用end才能解决,否则,如果视频为空,它将拒绝