Async.series 不适用于 fs.readFile

Async.series doesn't work with fs.readFile

本文关键字:fs readFile 适用于 不适用 series Async      更新时间:2023-09-26

第一步,我想将文件加载到名为"file"的变量中,然后在第二步,do response.write(file)
为了实现这一点,我使用了async.series,但我的代码有问题。

这是我用来启动服务器的代码:

var http = require("http"),
    fs = require('fs'),
    async = require('./js/async.js');
var onRequest = function(request,response) {
  response.writeHead(200,{ "Content-Type": "text/html; charset=utf-8" });
  var file;            // 'file' declared
  var main = function(callback) {
    fs.readFile('.''html''admin.html','utf-8',function(err,data) {
      file = data;     // 'file' is given content of admin.html
      console.log('2 >> ' + typeof file);
    });
    callback(null);
  }
  console.log('1 >> ' + typeof file);
  async.series([
    main                       
  ], function() {      // At this point 'file' is still undefined, that's odd
    response.end();    // 'cause it's a callback and should be fired after 'main'
    console.log('3 >> ' + typeof file);
  });
}
http.createServer(onRequest).listen(80);


问题在于主题 - async.series 没有像我希望的那样工作:在触发来自 async.series 的回调后,"main"函数中的 fs.readFile 返回数据。

我得到这个输出:

1 >> undefined
3 >> undefined
2 >> string

虽然我期望:

1 >> undefined
2 >> string
3 >> string


问题出在哪里?

尝试将回调添加到 readFile

var main = function(callback) {
    fs.readFile('.''html''admin.html','utf-8',function(err,data) {
      file = data;     // 'file' is given content of admin.html
      console.log('2 >> ' + typeof file);
      callback(null);
    });  
}

也许在我们的情况下最好使用瀑布?,像这样

async.waterfall([
  function (callback) {
    fs.readFile('.''html''admin.html','utf-8', function (err, data) {
      callback(err, data);  
    });
  }  
], function (err, file) {
  response.end();  
})