[英]how to update objects with array map async/await
我希望我的方法生成一個代表目錄樹的 js object,我使用目錄樹: https://www.npmjs.com/package/directory-tree 。 它有效。
我的問題是當我想計算視頻文件 (MP4) 的持續時間時,我想為每個項目添加一個屬性“持續時間”,但 id 不起作用,因為它返回 promise。
計算持續時間我使用get-video-duration: https://www.npmjs.com/package/get-video-duration
這是代碼
const {getVideoDurationInSeconds} = require('get-video-duration');
const dirTree = require("directory-tree");
async function getVideoDuration(path) {
const duration = await getVideoDurationInSeconds(path);
return duration;
}
const anAsyncMethod = async (item, PATH, stats) => {
if (item.type === 'file' && item.extension === '.mp4') {
const duration = await getVideoDuration(item.path);
item.duration = duration;
console.log(item); // it works here
return item;
}
}
const getCourseVideos = async (path) => {
const tree = await dirTree(path, { extensions: /\.mp4/,} , anAsyncMethod);
return (tree);
};
getCourseVideos('/PATH/TO/YOUR/FOLDER/OF/VIDEOS').then((tree)=> {
console.log(tree);
});
實際 output 的示例:
{
"path": "/MY/PATH/HERE",
"name": "react",
"children": [
{
"path": "/MY/PATH/HERE/lesson",
"name": "lesson",
"children": [
{
"path": "/MY/PATH/HERE/lesson/lesson10.mp4",
"name": "lesson10.mp4",
"size": 38642184,
"extension": ".mp4",
"type": "file"
},
{
"path": "/MY/PATH/HERE/lesson/lesson11.mp4",
"name": "lesson11.mp4",
"size": 41421609,
"extension": ".mp4",
"type": "file"
}
}
],
"size": 17042089152,
"type": "directory"
}
...
您可以在承諾字符串中添加一個中間操作,然后 go 拋出樹來尋找視頻。 是這樣的:
getCourseVideos('/PATH/TO/YOUR/FOLDER/OF/VIDEOS')
.then(async (tree)=> {
const queue = [tree];
while (queue.length > 0) {
const item = queue.shift();
if (item.children) {
for (let it of item.children) {
queue.push(it)
}
} else if (item.type === 'file') {
item = await anAsyncMethod(item.path);
}
}
return tree;
})
.then(tree => console.log(tree));
我找到了一個解決方案:這是新代碼
const {getVideoDurationInSeconds} = require('get-video-duration');
const dirTree = require("directory-tree");
async function getVideoDuration(path) {
const duration = await getVideoDurationInSeconds(path);
return duration;
}
const recursiveAsync = async (item, PATH, stats) => {
if (item.type === 'directory') {
item.children = await Promise.all(item.children.map(async (item) => {
return recursiveAsync(item);
}));
}
if (item.type === 'file' && item.extension === '.mp4') {
const duration = await getVideoDuration(item.path);
item.duration = duration;
}
return item;
}
const getCourseVideos = async (path) => {
const tree = dirTree(path, {extensions: /\.mp4/,});
await Promise.all(tree.children.map(async (item) => {
return recursiveAsync(item);
}));
return tree;
};
getCourseVideos('/PATH/TO/YOUR/FOLDER/OF/VIDEOS').then((tree) => {
console.log(tree);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.