javascript - 如何找到异步数据的总和?
问题描述
我正在尝试查找文件夹中所有 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;
解决方案
您只想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);
}
推荐阅读
- pandas - 如何删除具有特定值的行
- php - Regex match longitude value that more than 18 digit
- java - MD5 TripleDES Ecryption in Java NoPadding Issue
- scala - CSV format is not loading in spark-shell
- flutter - How to provide data with provider using nested data models [List > Item > Sublist > SubItem]
- matlab - If I have 4 coordinates making a rectangle, how can I color in that area?
- flutter - 在 Flutter 的网页中显示对话框提示
- bash - 查明我列表中的文件夹是否真的存在于我的文件夹中
- javascript - 如何将 HTML 输入中的文件加载到 Emscripten 的 MEMFS 文件系统中?
- javascript - 将对象转换为数组对象,但按键名字符数减少