Node.js Node JS Promise.all异步更新JSON对象数组中的属性

Node.js Node JS Promise.all异步更新JSON对象数组中的属性,node.js,webvtt,promise.all,Node.js,Webvtt,Promise.all,我不熟悉JS和Node.JS,我正在做一个个人项目,使用Azure Translator API翻译webVTT字幕文件——为此,我使用Node webVTT npm包解析/编译webVTT文件。解析操作提供了一个JSON对象,该对象包含数千个提示的数组,如下所示: [ { "identifier":"", "start":60, "end":61,

我不熟悉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":""
      }
]
为了转换“text”属性,我使用代码并对translateText函数应用了以下更改:

  • 我创建了一个承诺,它返回一个“提示”对象(而不仅仅是翻译的文本)
  • 我将一个“提示”对象作为输入和要翻译的语言
然后,我使用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');
  });
e、 我正在寻找一种只使用承诺的方法,并获得您的建议来优化此代码

mapAsync(webVTT.cues)
      .then(compile(webVTT))
      .then((data) => writeFileSync('./translated_fr.vtt', data, 'utf8'));

将async Wait函数转换为promise这一个函数中是否有任何问题?上面的代码没有任何具体问题,只是我不太喜欢async/promise之间的混合-我想得到像fs.createReadStream这样干净的东西('./mysubtitles.srt').pipe(parse()).pipe(resync(-100)).pipe(stringify({format:'WebVTT'})).pipe(fs.createWriteStream('./mysubtitles.vtt'))
// 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();