以下代码可以正常使用:
var fs = require('fs');
var async = require('async');
var addErrParm = function (err, done) {return function(exists) {
done(err, exists);
}}
function testAsync() {var response = '';
function checkIfTheFileExists(done) {
fs.exists('file.txt', addErrParm(null, done));
}
function readTheFile(exists, done) {
if (!exists) {
done('notFound');
} else {
fs.readFile('file.txt', 'utf8', done);
}
}
function showTheFile(err) {
if (err) {
response = err;
} else {
response = 'file was read';
}
console.log(response);
}
async.waterfall([ // <-- waterfall
checkIfTheFileExists,
readTheFile
], showTheFile);
}
testAsync() // "file was read"
以下似乎不起作用。唯一的区别是第一次使用async.waterfall而不是async.series。
var fs = require('fs');
var async = require('async');
var addErrParm = function (err, done) {return function(exists) {
done(err, exists);
}}
function testAsync() {var response = '';
function checkIfTheFileExists(done) {
fs.exists('file.txt', addErrParm(null, done));
}
function readTheFile(exists, done) {
if (!exists) {
done('notFound');
} else {
fs.readFile('file.txt', 'utf8', done);
}
}
function showTheFile(err) {
if (err) {
response = err;
} else {
response = 'file was read';
}
console.log(response);
}
async.series([ // <-- this is the only line of code that is different.
checkIfTheFileExists,
readTheFile
], showTheFile);
}
testAsync() // <-- nothing was shown on the console, not even a blank line.
async.series版本未记录对控制台的任何响应。什么导致async.series版本没有响应?
我还尝试了一个使用async.parallelLimit的版本,将限制设置为1.我希望它由于限制而在系列中运行任务,但在控制台上又没有收到任何内容。这是async.parallelLimit版本:
var fs = require('fs');
var async = require('async');
var addErrParm = function (err, done) {return function(exists) {
done(err, exists);
}}
function testAsync() {var response = '';
function checkIfTheFileExists(done) {
fs.exists('file.txt', addErrParm(null, done));
}
function readTheFile(exists, done) {
if (!exists) {
done('notFound');
} else {
fs.readFile('file.txt', 'utf8', done);
}
}
function showTheFile(err) {
if (err) {
response = err;
} else {
response = 'file was read';
}
console.log(response);
}
async.parallelLimit([ // <--- this line is different
checkIfTheFileExists,
readTheFile
], 1, showTheFile); // <--- and this line is different. I added the "1".
}
testAsync() // <--- produces nothing on the console.
该文件确实存在于所有三个测试用例中。
答案 0 :(得分:2)
async.series版本未记录对控制台的任何响应。什么导致async.series版本没有响应?
你误解了系列的语义。它像瀑布一样依次排列,但与瀑布不同,每个工人的功能完全独立。因此,checkIfTheFileExists
的结果不会传递给readTheFile
。系列没有这样做。