如何解决节点JS Promise.all异步更新JSON对象数组中的属性
我是JS和Node.js的新手,并且我正在一个个人项目中使用Azure Translator API翻译webVTT字幕文件-为此,我使用node-webvtt npm包来解析/编译webVTT文件。解析操作提供了一个JSON对象,其中包含成千上万个如下所示的线索数组:
[
{
"identifier":"","start":60,"end":61,"text":"My text to be translated #1","styles":""
},{
"identifier":"","start":110,"end":111,"text":"My text to be translated #2","styles":""
}
]
要翻译“文本”属性,我使用代码sample provide by Microsoft on GitHub,并将以下更改应用于transformText函数:
然后我跟随code provided here,它使用Promise.all和item.map的组合通过我的异步translateText函数翻译所有提示文本
这是我的index.js的代码-可以工作,但是我不太喜欢这段代码,并且我敢肯定它可以优化并且看上去更好。
require('dotenv').config();
const { readFileSync,writeFileSync } = require('fs');
const { parse,compile } = require('node-webvtt');
const { translateText } = require('./translate.js');
const inputStr = readFileSync('./subtitles.vtt','utf8');
const webVTT = parse(inputStr,{ Meta: true,strict : true });
const MSTranslateAsync = async (cue) => {
return translateText(cue,'fr')
}
const mapAsync = async (vttCues) => {
return Promise.all(vttCues.map(cue => MSTranslateAsync(cue)))
}
mapAsync(webVTT.cues)
.then(() => {
outStr = compile(webVTT);
writeFileSync('./translated_fr.vtt',outStr,'utf8');
});
例如我正在寻找一种仅使用Promises并获得您的建议来优化此代码的方法
mapAsync(webVTT.cues)
.then(compile(webVTT))
.then((data) => writeFileSync('./translated_fr.vtt',data,'utf8'));
解决方法
// not required but I'm using async version of fs in my projects
const fsAsync = require('fs').promises;
//
const compileAndWrite = async ()=>{
await mapAsync(webVTT.cues);
let outStr = compile(webVTT); //let outStr = await compile(webVTT);
await fsAsync.writeFile('./translated_fr.vtt',outStr,'utf8'); // ou use writeFileSync()
};
compileAndWrite();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。