首页 > 解决方案 > 使用 async/await 并行执行方法

问题描述

在为 Angular 应用程序运行 gradle 命令时,我正在构建多种语言。

下面是用于构建所有本地化文件的代码。

调用该buildAllLanguageVersion()方法通过迭代所有可用的构建语言来一一构建语言。

   function buildAllLanguageVersion() {
    return new Promise(async (accept, reject) => {
        const doneLanguages = [];
        const applicationBase = "APPNAME";
        for (let language of buildLanguages) {
         
            const ret = await buildingLanguage(language);
            doneLanguages.push(ret);
        }
        accept(doneLanguages);
    });
}

        
        
    function buildingLanguage(buildLanguage) {
        return new Promise(accept => {
            console.log("Language building" + buildLanguage);
            const languagePath = path.resolve(`./src/i18n/messages.${buildLanguage}.xlf`);
            const languageFile = fs.existsSync(languagePath) ? buildLanguage : "en";
            if (languageFile !== buildLanguage && !fs.existsSync(languagePath)) {
                console.error(
                    "Language file does not exist." +
                        buildLanguage
                );
            }
           exec.exec(`${folder} build --configuration=dynamic`, (error, stdout, stderror) => {
                if (error) {
                    throw "Build failed: " + error;
                }
                accept(buildLanguage);
            });
        });
    }
    
    

当我必须按顺序构建语言时,上面的代码工作正常。构建一种语言几乎需要 3-5 分钟。我现在在应用程序中使用 7 种不同的语言。

我的问题是如何并行调用该方法,以便减少构建时间。

到目前为止,我已经尝试Promise.all()buildAllLanguageVersion()方法中并行调用该方法buildingLanguage(),但这并没有帮助。这些方法一次被调用(并行),但构建失败并出现以下错误。

14:31:17 D:\ls\workspace\Generic_commit\APP\app-name\tools\build-all.js:129
14:31:17 throw "Build failed: " + error;
14:31:17 ^
14:31:17 Build failed: Error: Command failed: D:\ls\workspace\Generic_commit\APP\app-name\node_modules\.bin\ng.cmd build --configuration=dynamic
14:31:17
14:31:17 ERROR in ngcc is already running at process with id 5252.
14:31:17 If you are running multiple builds in parallel then you should pre-process your node_modules via the command line ngcc tool before starting the builds;
14:31:17 See https://v9.angular.io/guide/ivy#speeding-up-ngcc-compilation.
14:31:17 (If you are sure no ngcc process is running then you should delete the lock-file at D:/ls/workspace/Generic_commit/APP/app-name/node_modules/@angular/compiler-cli/ngcc/_ngcc_lock_file_.)

我尝试删除,_ngcc_lock_file_但没有帮助。

标签: javascriptparallel-processingasync-await

解决方案


推荐阅读