【发布时间】:2021-10-17 17:42:26
【问题描述】:
get-video-duration 是一个获取视频时长的 npm 模块。
const { getVideoDurationInSeconds } = require('get-video-duration')
// From a local path...
getVideoDurationInSeconds('video.mov').then((duration) => {
console.log(duration)
})
我想使用此模块从视频路径数组中获取所有视频的总时长。
function getTotals(video_Array) {
let total_duration = 0;
video_Array.forEach(video => {
getVideoDurationInSeconds(video).then(duration => {
total_duration += duration;
})
})
}
问题是getVideoDurationInSeconds 是异步的,我不能简单地返回结果。
function getTotals(video_Array) {
let total_duration = 0;
video_Array.forEach(video => {
getVideoDurationInSeconds(video).then(duration => {
total_duration += duration;
})
})
return total_duration;
}
如何获得最终结果?提前谢谢!
【问题讨论】:
-
使用
map而不是forEach,创建一个包含promise的数组,然后使用promise.all。我记不太清了,但forEach不能很好地处理承诺或异步代码
标签: javascript node.js asynchronous npm promise