简体   繁体   中英

How to handle properly the Gulp's Task function in NodeJS API?

Currenly, I know only one working method of runnig the Gulp task without gulpfile and CLI:

import Gulp from "gulp";

const TASK_NAME: string = "EXAMPLE_TASK";

Gulp.task(TASK_NAME, Gulp.parallel([
    // ... imported task fuctions ...
]);

Gulp.task(TASK_NAME)(
    (error?: Error | null): void => { if (isNeitherUndefinedNorNull(error)) { console.error(error); } }
);

It is not the subject of question; I just explained what I doing and why my code is such as, but if you know the better method of executing of Gulp task without gulpfile and CLI, please let me now.

Now about the subject. Until recently, the last part of the code ( Gulp.task(TASK_NAME)(/*... */) ) has not been rejected by no-floating-promises rule if typescript-eslint . By after latest update of @types/gulp (or typescript-eslint - now it's hard to explore which one) typescript-eslint warn me:

Promises must be handled appropriately or explicitly marked as ignored with the void operator

there. I know it's not the false alarm. Sometimes my Gulp tasks chain broken with unhandled promise rejection , but it was not obvious where promise was. Now I had the hint, but it's still unclear.

I explored that:

  1. Gulp.task() returned the Undertaker.TaskFunctionWrapped
  2. TaskFunctionWrapped extends the TaskFunctionBase
  3. TaskFunctionBase is (done: TaskCallback): ReturnType<AsyncTask>;
  4. The AsyncTask is:
export type AsyncTask<R = any> =
  ((done: VoidCallback) => void)
  | ((done: Callback<R>) => void)
  | (() => ChildProcess | EventEmitter | Observable<R> | PromiseLike<R> | Stream);

According documentation , the task function must return the ChildProcess , EventEmitter , Observable , Promise or Stream . But how to handle it? Gult.task()() is not thenable:

在此处输入图像描述

Error texting:

TS2339: Property 'catch' does not exist on type 'void | EventEmitter | ChildProcess | Stream | Observable | PromiseLike'.

Update: @TheBumpaster solution try

Unfortunately, the @typescript/eslint still tells me "Promises must be handled appropriately or explicitly marked as ignored with the void operator" in Gulp.task(ProjectBuilder.GULP_TASK_NAME) line.

const task: Promise<void> = new Promise<void>((resolve: () => void, reject: (error: Error) => void): void => {

  console.log("checkpoint1");

  Gulp.task(ProjectBuilder.GULP_TASK_NAME)(
      (error?: Error | null): void => {

        if (isNeitherUndefinedNorNull(error)) {
          console.log("checkpoint2-A");
          reject(error);
        } else {
          console.log("checkpoint2-B");
          resolve();
        }
      }
  );
});

task.catch((error: Error): void => { console.error(error); });

I intentionally rise the error in some of gulp plugins. The project builder reaches the "checkpoint1" but neither "checkpoint2-A" nor "checkpoint2-B" . The output is:


D:\XXX\node_modules\async-done\index.js:18
    throw err;
    ^

Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({
  uid: 0,
  name: '<anonymous>',
  branch: false,
  error: AssertionError [ERR_ASSERTION]:

Maybe it's indirectly indicates that @typescript/eslint yelling is not a lip service...

You should have been aware of the fact that handling promises are required for 'catch' function.

According to https://gulpjs.com/docs/en/getting-started/async-completion/

Gulp.Task(ProjectBuilder.GLUP_TASK_NAME)( (error) => { if ( error ) { 
  throw new Error(error); } // this is already executed 
 }

const task = new Promise( (resolve, reject ) => {

Gulp.Task(ProjectBuilder.GLUP_TASK_NAME)( (error) => { if ( error ) { reject(error) } resolve() }

});

task().then().catch(e => console.error(e))

Update on comment:

Perhaps this example might help you demonstrate what have I meant with my code above.

const gulp = require("gulp")
const taskName = "task-name"

// Example callback
gulp.task(taskName, (error) => {
    if (error) {
        console.error(error);
    }
    // It's already executed here
    console.log(taskName)
});

// Example Promise object
const Task = new Promise( (resolve, reject) => {
    gulp.task(taskName, (error) => {
        if (error) {
            reject(error)
        }
        resolve(taskName)
    });
});

Task.then(console.log).catch(console.error)

// Example Promise function
const performTask = (_taskName) => {
    return new Promise( (resolve, reject) => {
        gulp.task(_taskName, (error) => {
            if (error) {
                reject(error)
            }
            resolve(_taskName)
        });
    });
}

performTask(taskName).then(console.log).catch(console.error)


// Example async/await with then/catch
const exampleServiceHandler = async (_taskName) => {
    // Perform actions here
    try {
        return await gulp.task(_taskName) // Resolve the task
    } catch (exception) {
        return exception;
    }
}

exampleServiceHandler(taskName)
.then(console.log)
.catch(console.error)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM