如何从异步数组中获得最终结果?



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;
}

我怎样才能得到最后的结果?提前感谢!

创建一个返回promise的函数然后用它来计算总持续时间

function getTotals(video_Array) {
let video_ArrayPromises=video_Array.map(video=> 
getVideoDurationInSeconds(video));
return Promise.all([video_ArrayPromises]).then((values) => {
//Calculate TotalDuration
return duratons.reduce((accumulator, currentValue) => accumulator + currentValue);
});
}
getTotals(['movie1.mov','movie2.mov']).then(totalDuration => {
//use total duration
});

map创建getVideoDurationInSeconds承诺数组,然后在Promise.all返回的值上创建reduce承诺数组,以获得最终总数。

附加文档

  • async/await

// Mock function that returns a promise.
// When it's resolved it will return a random number
// muliplied by the element passed in through the function arguments
function getVideoDurationInSeconds(el) {
const rnd = Math.floor(Math.random() * (10 - 1) + 1);
return new Promise((res, rej) => {
setTimeout(() => {
console.log(el * rnd);
res(el * rnd);
}, 1000);
});
}
async function getTotals(videoArray) {
// `map` over the elements of the video array
// and create a new array of promises
const promises = videoArray.map(el => getVideoDurationInSeconds(el));
// Wait until all the promises have resolved
const data = await Promise.all(promises);
// Then return the sum of each total in the data array
return data.reduce((acc, c) => acc += c, 0);
}
(async function main() {
console.log(`Total: ${await getTotals([1, 2, 3, 4])}`);
}());

返回一个请求数组,并使用reduce获取总时间。

// Array
function getTotalTime() {
return videoList.map(async (video) => await getVideoDurationInSeconds(video));
}

// Just invoke whereever you want..
await Promise.all(getTotalTime()).then(result => {
let totalTime = result.reduce((acc, cv) => acc + cv, 0); // 0 = default value
})

最新更新