【问题标题】:Async.series doesn't work with fs.readFileAsync.series 不适用于 fs.readFile
【发布时间】:2014-11-29 02:15:35
【问题描述】:

第一步,我想将文件加载到名为“file”的变量中,然后,在第二步, 做 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 不能像我预期的那样工作:'main' 函数中的 fs.readFile 在触发来自 async.series 的回调后返回数据。

我得到这个输出:

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

虽然我期望:

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


有什么问题?

【问题讨论】:

    标签: javascript node.js asynchronous


    【解决方案1】:

    尝试添加回调到 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();  
    })
    

    【讨论】:

      猜你喜欢
      • 2016-01-25
      • 1970-01-01
      • 2013-12-09
      • 2012-06-02
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-04
      相关资源
      最近更新 更多