运行如何作为Gulp4中的任务?

How to run function as a task in Gulp 4?

如何在 Gulp 执行期间 运行 函数,以便 Gulp 将该函数视为任务(将其打印到日志中)?

这是我的例子 gulpfile.js:

async function doStaff(todo) {
  // ...
}

exports.default = async () => {
  // Some asynchronous logic which gets the subtasks
  const todos = await myAPI.getTodos();

  await Promise.all(todos.map(async todo => {
    const subTask = doStuff.bind(todo);
    subTask.displayName = `todo «${todo.name}»`;
    await subTask(); // I want it to run as a Gulp task
  }));
};

预期Gulp输出:

Starting 'default'...
Starting 'todo «foo»'...
Starting 'todo «bar»'...
Finished 'todo «foo»' after 1.2s
Finished 'todo «bar»' after 1.5s
Finished 'default' after 2s

实际 Gulp 输出:

Starting 'default'...
Finished 'default' after 2s

原因:我的子任务列表无法同步检索并且 Gulp doesn't support asynchronous configuration 并且不支持它。尽管如此,我还是希望在 Gulp 输出中看到子任务的进度和时间安排。

将函数包装到gulp.seriesgulp.parallel中,使Gulp显示其状态。它看起来不像是一个优雅的解决方案,但它是我找到的最好的解决方案。

这是一个通用的例子:

function runGulpTask(func) {
  return new Promise((resolve, reject) => gulp.series(func)(error => {
    if (error) {
      reject(error);
    } else {
      resolve();
    }
  }));

  // The same solution using built-in Node.js functions:
  // const {promisify} = require('util');
  // return promisify(gulp.series(func))();
}

async function doStaff(todo) {
  // ...
}

exports.default = async () => {
  const todos = await myAPI.getTodos();

  await Promise.all(todos.map(async todo => {
    const subTask = doStuff.bind(todo);
    subTask.displayName = `todo «${todo.name}»`;
    await runGulpTask(subTask);
  }));
};

Gulp 输出与预期输出相同。

这是一个更具体的例子:

async function doStaff(todo) {
  // ...
}

exports.default = async () => {
  const todos = await myAPI.getTodos();

  const subTasks = todos.map(todo => {
    const subTask = doStuff.bind(todo);
    subTask.displayName = `todo «${todo.name}»`;
    return subTask;
  });

  await new Promise((resolve, reject) => gulp.parallel(...subTasks)(error => {
    if (error) {
      reject(error);
    } else {
      resolve();
    }
  }));
  // Or using built-in Node.js functions:
  // const {promisify} = require('util');
  // await promisify(gulp.parallel(...subTasks))();
};