简体   繁体   English

如何在 NodeJS API 中正确处理 Gulp 的任务 function?

[英]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:目前,我只知道一种在没有gulpfile和 CLI 的情况下运行 Gulp 任务的工作方法:

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.我只是解释了我在做什么以及为什么我的代码是这样的,但是如果您知道在没有gulpfile和 CLI 的情况下执行 Gulp 任务的更好方法,请现在告诉我。

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 .直到最近,如果 typescript-eslint ,代码的最后一部分( Gulp.task(TASK_NAME)(/*... */) )还没有被no-floating-promises规则拒绝 By after latest update of @types/gulp (or typescript-eslint - now it's hard to explore which one) typescript-eslint warn me:@types/gulp gulp (或typescript-eslint - 现在很难探索哪一个)的最新更新之后,typescript typescript-eslint警告我:

Promises must be handled appropriately or explicitly marked as ignored with the void operator必须正确处理承诺或使用void运算符明确标记为忽略

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.有时我的 Gulp 任务链因unhandled promise rejection而中断,但 promise 的位置并不明显。 Now I had the hint, but it's still unclear.现在我有了提示,但仍不清楚。

I explored that:我对此进行了探索:

  1. Gulp.task() returned the Undertaker.TaskFunctionWrapped Gulp.task()返回了Undertaker.TaskFunctionWrapped
  2. TaskFunctionWrapped extends the TaskFunctionBase TaskFunctionWrapped扩展了TaskFunctionBase
  3. TaskFunctionBase is (done: TaskCallback): ReturnType<AsyncTask>; TaskFunctionBase is (done: TaskCallback): ReturnType<AsyncTask>;
  4. The AsyncTask is: AsyncTask是:
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 .根据文档,任务 function 必须返回ChildProcessEventEmitterObservablePromiseStream But how to handle it?但是如何处理呢? Gult.task()() is not thenable: Gult.task()()则不可:

在此处输入图像描述

Error texting:短信错误:

TS2339: Property 'catch' does not exist on type 'void | TS2339:“void |”类型上不存在属性“catch” EventEmitter |事件发射器 | ChildProcess |子进程 | Stream | Stream | Observable |可观察 | PromiseLike'.许诺”。

Update: @TheBumpaster solution try更新:@TheBumpaster 解决方案尝试

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.不幸的是,@typescript/eslint 仍然在Gulp.task(ProjectBuilder.GULP_TASK_NAME)行中告诉我“必须正确处理承诺或使用void运算符明确标记为忽略”。

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.我故意在一些 gulp 插件中增加错误。 The project builder reaches the "checkpoint1" but neither "checkpoint2-A" nor "checkpoint2-B" .项目生成器到达"checkpoint1"但既没有到达"checkpoint2-A"也没有到达"checkpoint2-B" The output is: output 是:


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...也许它间接表明@typescript/eslint 大喊大叫不是口头上的……

You should have been aware of the fact that handling promises are required for 'catch' function.您应该已经知道“catch” function 需要处理承诺这一事实。

According to https://gulpjs.com/docs/en/getting-started/async-completion/根据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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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