简体   繁体   English

节点-异步功能未输出

[英]node - async functions are not outputting

Running v0.12.7 运行v0.12.7

None of the default fs functions are running. 默认的fs函数均未运行。

Example is fs.readdir 示例是fs.readdir

grunt.registerTask('commentTest', function (arg) {
    var fs = require('fs');

    console.log('Outside Test 1');
    console.warn('Outside Test 2');

    fs.readdir('./', function (err, files) {
        console.log('Inside Test 1');
        console.warn('Inside Test 2');
        colsole.log(files);
    });

});

So, if I run this, in the console I get 所以,如果我运行它,在控制台中

Outside Test 1
Outside Test 2

But nothing in the callback. 但是回调中什么也没有。

If I run... 如果我跑...

grunt.registerTask('commentTest', function (arg) {
    var fs = require('fs');

    var files = fs.readdirSync('./');

    console.log(files);

});

I get what is expected from the job. 我得到这份工作的期望。

Something is breaking the async and I don't know what. 某种东西正在打破异步,我不知道是什么。 I've completely cleared out my grunt file and started from scratch, but I can't figure it out. 我已经完全清除了grunt文件并从头开始,但是我无法弄清楚。

I'm looking at maybe a config issue? 我正在查看配置问题?

This occurs because Grunt is unaware of the asynchronous operation and will interrupt it, believing that the task has completed after function (arg) exits. 发生这种情况是因为Grunt不知道异步操作,并且会认为function (arg)退出后任务已经完成,因此会中断异步操作。

You'll have to inform Grunt that the task is asynchronous by calling this.async() , as well as when the task is done so it can proceed to the next. 您必须通过调用this.async()通知Grunt该任务是异步的,以及何时done该任务done以便可以继续执行下一个任务。

grunt.registerTask('commentTest', function (arg) {
    // tell grunt this task is asynchronous
    var done = this.async();
    var fs = require('fs');

    console.log('Outside Test 1');
    console.warn('Outside Test 2');

    fs.readdir('./', function (err, files) {
        console.log('Inside Test 1');
        console.warn('Inside Test 2');
        colsole.log(files);

        // tell grunt when the task is actually done
        // also of the `err` if one occurred
        done(err ? false : null);
    });
});

Grunt documents this requirement in their page on Creating Tasks , under the heading " Why doesn't my asynchronous task complete? " Grunt在其“ 创建任务 ”页面上的“ 为什么我的异步任务未完成? ”标题下记录了这一要求。

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

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