0

How to run a function during a Gulp execution so that Gulp treats the function as a task (prints it to the log)?

Here is an example of my 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
  }));
};

Expected Gulp output:

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

Actual Gulp output:

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

Why: My list of subtasks can't be retrieved synchronously and Gulp doesn't support asynchronous configuration and isn't going to support it. Never the less I want to see the subtasks progress and timing in the Gulp output.

Finesse
  • 9,793
  • 7
  • 62
  • 92

1 Answers1

0

Wrap the function into gulp.series or gulp.parallel to make Gulp display its status. It doesn't look like an elegant solution but it's the best I've found.

Here is a universal example:

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);
  }));
};

The Gulp output is the same as the expected output.

And here is a more specific example:

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))();
};
Finesse
  • 9,793
  • 7
  • 62
  • 92