【问题标题】:Async completion error when function called, or callback not a function when called on default function调用函数时出现异步完成错误,或者在默认函数上调用时回调不是函数
【发布时间】:2022-10-24 16:42:56
【问题描述】:

我正在尝试创建一个调用其他一些函数的函数:

copy = () => {
    copyHtml();
    copyCss();
    copyJs();
    copyImg();
}
exports.copy = copy;

使用gulp copy,该功能有效,但我收到此错误:

以下任务未完成:复制。 您是否忘记发出异步完成信号?

我不习惯它,搜索后我只是改变了我的功能,如下所示,它可以正常工作:

copy = (done) => {
    copyHtml();
    copyCss();
    copyJs();
    copyImg();
    done();
}
exports.copy = copy;

然后我将它添加到我的默认函数中:

defaultFunction = () => {
    copy();
    browsersyncServe();
}
exports.default = defaultFunction;

我的问题是当我用 gulp 调用默认函数时:

done 不是函数

如果我在默认函数中直接调用copyHtmlcopyCsscopyJscopyImg,它可以正常工作并且不会出错。

我错过了什么?

【问题讨论】:

    标签: javascript node.js callback gulp


    【解决方案1】:

    copy 函数在其参数中需要一个回调,但您在 defaultFunction 中调用它时不带参数,这将是未定义的。这就是为什么它抱怨“完成不是一个功能”。

    看起来你所有的功能都是同步的,done 没用。所以你可以将一个虚拟函数传递给copy

    // the defaultFunction should call the done callback on finish as well
    defaultFunction = (done) => {
        copy(() => {});
        browsersyncServe();
        done();
    }
    exports.default = defaultFunction;
    

    顺便说一句,在 gulp 任务中逐个执行操作的更好方法是使用 seriescompose 函数,每个要组合的函数都需要接受一个回调函数:

    const { series } = require('gulp');
    
    function copyHtml(done) {
      // .....
      done();  // callback when it is done
    }
    
    copy = series(
        copyHtml,
        copyCss,
        copyJs,
        copyImg
    );
    
    exports.copy = copy;
    
    exports.default = series(copy, browsersyncServe);
    

    【讨论】:

    • 你不应该使用copy(() => { browsersyncServe(); done(); }),而不是传递一个虚拟函数吗?甚至可能使用 nodeback 样式的错误传播?
    【解决方案2】:

    当你调用它时:

    defaultFunction = () => {
        copy();
        browsersyncServe();
    }
    exports.default = defaultFunction;
    

    你打电话给copy() 没有任何参数。因此在这里:

    copy = (done) => {
        copyHtml();
        copyCss();
        copyJs();
        copyImg();
        done();
    }
    exports.copy = copy;
    

    done 未正确定义。这就是错误。

    你可以通过done:

    defaultFunction = (done) => {
        copy(done);
        browsersyncServe();
    }
    exports.default = defaultFunction;
    

    【讨论】:

    • 如果复制需要 done 回调,因为它是异步的,则不应在它之后立即调用 browsersyncServe
    猜你喜欢
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 2017-11-27
    相关资源
    最近更新 更多