![](/img/trans.png)
[英]Wait for function to end (in async.series) doesn't work as expected
[英]Async.series doesn't work with fs.readFile
第一步,我想將文件加載到名為“ 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無法正常工作,正如我期望的那樣:觸發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);
});
}
也許在我們的情況下最好使用Waterfall?,像這樣
async.waterfall([
function (callback) {
fs.readFile('.\\html\\admin.html','utf-8', function (err, data) {
callback(err, data);
});
}
], function (err, file) {
response.end();
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.