简体   繁体   中英

node - async functions are not outputting

Running v0.12.7

None of the default fs functions are running.

Example is 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.

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.

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.

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? "

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