2015-10-15 64 views
0

运行v0.12.7节点 - 异步功能不输出

没有默认的fs函数正在运行。

例子是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); 
    }); 

}); 

所以,如果我跑这一点,在控制台中我得到

Outside Test 1 
Outside Test 2 

但没有回调。

如果我跑......

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

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

    console.log(files); 

}); 

我得到了从作业的预期。

有些东西打破了异步,我不知道是什么。我已经彻底清除了我的咕噜文件并从头开始,但我无法弄清楚。

我在看可能是一个配置问题?

+0

“[为什么我的异步任务完成了吗?](http://gruntjs.com/creating-tasks #why-doesn-t-my-asynchronous-task-complete)“ –

+0

@JonathanLonowski - 为什么不作出回答? – jfriend00

回答

1

发生这种情况是因为Grunt不知道异步操作并会中断它,认为该任务在function (arg)退出后已完成。

您必须通过呼叫this.async()以及任务为done来通知Grunt该任务是异步的,因此可以继续下一步。

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); 
    }); 
}); 

咕噜文档这一要求在其上Creating Tasks页,标题下的“Why doesn't my asynchronous task complete?

+0

Bummer这没有出现在我的谷歌搜索。谢谢,不过。 – Plummer