最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Node.js异步功能是否并行执行?

网站源码admin20浏览0评论

Node.js异步功能是否并行执行?

Node.js异步功能是否并行执行?

下面的代码用于:

  1. 转换一些视频并将其存储在转换后的文件夹中。
  2. CONCATENATE转换后的视频。
  3. 清除转换后的文件夹。

BUT当前,在执行代码时,它在转换时会串联在一起,并最终引发错误。我需要按其各自的顺序优先执行每个功能。

const glob = require('glob');
const exec = require('child_process').exec;
const { unlink } = require("fs").promises;

function start(index) {


  const path = `./files/${index}`;
  const ConvertedVideos=path+"/converted/*.mp4";
  const videos = glob.sync(path+"/videos/*.mp4");
  const outputnoaudio = path+"/outputnoaudio.mp4";




  //THIS IS THE ORDER OF EXECUTION

  await convertVideos()
  await withFfmpegConcatVideo()
  await clearConverted()



  //HERE THE DEFINITION OF EACH FUNCTION

  async function convertVideos() {
    return new Promise((resolve) => {

      console.log('>>>Starting conversion!!!');
      const promises = videos.map(
        (video, index) => {
          var command = `ffmpeg -i ${video} -c:v libx264 -vf scale=1920:1080 -r 60 -c:a aac -ar 48000 -b:a 160k -strict experimental -f mp4 ./converted/${index}.mp4`;

          return new Promise((resolve) => {
            exec(command, (error, stdout, stderr) => {
              if (error) {
                console.warn(error);
              }
              resolve(stdout ? stdout : stderr);
              console.log('Converted video', index);
            });
          });
        }
      )
      Promise.all(promises);
      resolve();
    })
  }

  async function withFfmpegConcatVideo() {
    return new Promise((resolve) => {

      console.log('Starting concatenation...');

      var converted = glob.sync(ConvertedVideos);

      console.log('There is ', converted.length, 'converted videos');

      if (converted.length > 0) {

        (async () =>
          await concat({
            output: outputnoaudio,
            videos: converted,
            transition: {
              name: 'fade',
              duration: 200
            }
          }))()
      }
      resolve(console.log('Conversion finished'));
    })
  }


  async function clearConverted() {

    return new Promise((resolve) => {

      const converted =
        glob.sync(ConvertedVideos)

      if (converted.length === 0)
        return Promise.resolve([])

      const promises =
        converted.map(v => unlink(v).then(_ => {
          v
        }))

      Promise.all(promises).then('Clean done.')
      resolve();
    })
  }
}

start(1);

我想保持干净且可重复使用的代码。您能帮我吗?

回答如下:

您的start功能看起来不正确,因为您缺少async运算符。

[为清楚起见,我建议将其更像C文件一样对待,并创建一个async function main() {}并在其中调用并await这三个函数。

convertVideos函数中,您正在调用Promise.all(),但您没有等待它。请注意,Promise.all()实际上也返回了一个promise,您必须等待它,但是为了等待它,周围的函数还必须具有async关键字。我在clearConverted函数中看到了相同的问题。

尝试等待您的Promise.all呼叫,看看是否可以解决您的问题。

发布评论

评论列表(0)

  1. 暂无评论