节点 - 异步函数不输出
node - async functions are not outputting
运行 v0.12.7
None 的默认 fs 函数是 运行ning.
例子是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);
});
我得到了这份工作的期望。
有什么东西打破了异步,我不知道是什么。我已经完全清除了我的 g运行t 文件并从头开始,但我无法弄清楚。
我在看可能是配置问题?
发生这种情况是因为 Grunt 不知道异步操作并会中断它,认为任务在 function (arg)
退出后已经完成。
您必须通过调用 this.async()
通知 Grunt 该任务是异步的,以及任务何时 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 在 Creating Tasks, under the heading "Why doesn't my asynchronous task complete?
的页面中记录了此要求
运行 v0.12.7
None 的默认 fs 函数是 运行ning.
例子是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);
});
我得到了这份工作的期望。
有什么东西打破了异步,我不知道是什么。我已经完全清除了我的 g运行t 文件并从头开始,但我无法弄清楚。
我在看可能是配置问题?
发生这种情况是因为 Grunt 不知道异步操作并会中断它,认为任务在 function (arg)
退出后已经完成。
您必须通过调用 this.async()
通知 Grunt 该任务是异步的,以及任务何时 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 在 Creating Tasks, under the heading "Why doesn't my asynchronous task complete?
的页面中记录了此要求