首页 > 解决方案 > 如何找到异步数据的总和?

问题描述

我正在尝试查找文件夹中所有 mp4 文件的总持续时间。但我找不到总和。

 const fs = require('fs');
const ffprobe= require('ffprobe');
const ffprobeStatic = require('ffprobe-static');
let sum=0;
const files=fs.readdirSync('./');
files.forEach(file=>{
    ffprobe(file,{ path: ffprobeStatic.path },(err,info)=>{
      if(err) console.log(err);
      sum+=file.streams[0].duration;
   });


console.log(sum)// 0;

标签: javascriptasynchronous

解决方案


您只想console.log(sum);在每个异步操作完成后调用。

因此,当您处理文件时,请保持已完成的异步操作总数(filesProcessedSoFar如下),并将其与预期的异步操作总数进行比较(在这种情况下,与预期的异步操作总数相同files.length,因为您正在为每个文件执行一个异步操作)。如果比较显示这两个值相等,则您知道所有作业都已完成,并且可以console.log(sum);在此时调用您的代码。

例子:

const fs = require('fs');
const ffprobe= require('ffprobe');
const ffprobeStatic = require('ffprobe-static');
let sum=0;
const files=fs.readdirSync('./');

// let's keep track of how many of the asynchronous jobs have finished, so we can call our printSum() function only when the last one finishes
let filesProcessedSoFar = 0;

files.forEach(file=>{
    ffprobe(file,{ path: ffprobeStatic.path },(err,info)=>{
      if(err) console.log(err);
      sum+=file.streams[0].duration;

      // if all files have been processed, it's time to print the sum
      filesProcessedSoFar++;
      if (filesProcessedSoFar == files.length) {
          printSum();
      }
   });


function printSum() {
    console.log(sum);
}

推荐阅读