Gulp javascript:如何在循环中进行多个异步调用

uurv41yg  于 2022-12-08  发布在  Gulp
关注(0)|答案(1)|浏览(154)

我在gulpfile.js中有以下任务:

'use strict';

const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');
const spsync = require('gulp-spsync-creds').sync;
const sppkgDeploy = require('node-sppkg-deploy');

const config = require('./dev-config.json');
var coreOptions = {
        siteUrl: config.coreOptions.siteUrl,
        appCatalog: config.coreOptions.appCatalog
    };
var creds = {
        username: config.creds.username,
        password: config.creds.password
    };

build.task('upload-single-app', {
  execute: (config) => {
      return new Promise((resolve, reject) => {
          const pluginList = require('./config/plugin-deployment.json');
          if (pluginList)
          {
            for (let i = 0; i < pluginList.plugins.length; i++) {
                  const folderLocation = `./plugins/` + pluginList.plugins[i].name;
                  for (let x = 0; x < pluginList.plugins[i].sites.length; x++) {

                        console.log(pluginList.plugins[i].sites[x]);
                        return gulp.src(folderLocation)
                        .pipe(spsync({
                            "username": creds.username,
                            "password": creds.password,
                            "site": coreOptions.siteUrl + pluginList.plugins[i].sites[x],
                            "libraryPath": coreOptions.appCatalog,
                            "publish": true
                        }))
                        .on('finish', resolve);
                      }//end inner for
              }// end for
          } else {
            console.log("Plugin list is empty");
          }
        });
  }
});

这是驱动这个过程的JSON数据:

{
  "plugins":
  [
    {
      "name": "Bluebeam.OpenRevuExtension.sppkg",
      "description":"some description",
      "version":"20.2.30.5",
      "sites":["sp_site1","sp_site2"]
    }
  ]
}

当我运行这段代码时,它成功地将软件包部署到站点1,而不是站点2。没有错误。

devbox:plugintest admin$ gulp upload-single-app
Build target: DEBUG
[14:51:48] Using gulpfile /src/plugintest/gulpfile.js
[14:51:48] Starting gulp
[14:51:48] Starting 'upload-single-app'...
sp_site1
[14:51:48] Uploading Bluebeam.OpenRevuExtension.sppkg
[14:51:50] Upload successful 1919ms
[14:51:51] Published file 982ms
[14:51:51] Finished 'upload-single-app' after 2.92 s
[14:51:51] ==================[ Finished ]==================
[14:51:52] Project plugintest version:1.0.0
[14:51:52] Build tools version:3.12.1
[14:51:52] Node version:v10.24.1
[14:51:52] Total duration:6.48 s

我对JS中的异步编码不是很熟悉,但是我想我可以重构,这样我就有两个独立的任务。一个将有循环JSON数据的逻辑......对于每个任务,它将调用一个独立的构建任务。类似如下:(伪代码)

build.task('main', {
     for each plugin in json file {
         for each site I need to deploy to {
             call build.task('upload_app');
             call build.task('deploy_app');
         }
     }
  });

问题

这是一个好的方法吗?你能给予我一些关于如何做到这一点的指点吗?

  • 谢谢-谢谢
2w2cym1i

2w2cym1i1#

出现当前行为的原因是,您有一个Promise,它在第一个站点完成时通过调用resolve来解析循环的第一次迭代。

依次

相反,在第二个循环中,每个站点都应该有一个Promise。结合async / await语法,等待循环中的每个Promise解析完毕,然后再继续下一个。

build.task("upload-single-app", {
  execute: async () => {
    const pluginList = require("./config/plugin-deployment.json");

    if (!pluginList) {
      return;
    }
    
    for (const { name, sites } of pluginList.plugins) {
      const folderLocation = `./plugins/${name}`;

      for (const site of sites) {
        // Here await each gulp pipeline to finish before moving on to the next.
        await new Promise((resolve) => {
          gulp
            .src(folderLocation)
            .pipe(
              spsync({
                username: creds.username,
                password: creds.password,
                site: coreOptions.siteUrl + site,
                libraryPath: coreOptions.appCatalog,
                publish: true,
              })
            )
            .on("finish", resolve);
        });
      }
    }
  },
});

并行

你也可以在每个站点上循环,用数组的map方法返回一个Promise,然后在一个数组中收集所有的承诺,并使用Promise.all()等待,直到所有的承诺都实现了。

build.task("upload-single-app", {
  execute: async () => {
    const pluginList = require("./config/plugin-deployment.json");

    if (!pluginList) {
      return;
    }
    
    const pluginBuilds = await Promise.all(pluginList.plugins.flatMap(({ name, sites }) => {
      const folderLocation = `./plugins/${name}`;

      return sites.map(site => new Promise((resolve) => {
        gulp
          .src(folderLocation)
          .pipe(
            spsync({
              username: creds.username,
              password: creds.password,
              site: coreOptions.siteUrl + site,
              libraryPath: coreOptions.appCatalog,
              publish: true,
            })
          )
          .on("finish", resolve);
      }));
    }));

    return pluginBuilds;
  },
});

相关问题