2017-05-04 65 views
3

執行以下代碼時,只執行async.series的第一個函數。nodejs:Async.series只執行第一個函數並停止

var fs = require("fs"); 
var async = require("async"); 
var buffer = new Buffer(10); 
var read = ""; 
var readByt; 
async.series([  
    function(callback) { 
     console.log("console: 1"); 
    }, 
    function (callback){ 
     console.log("console: 2"); 
    } 
],function(){}); 

的輸出如下給出:

c:\>node fr.js 
}}}c:/log.txt 
File closed successfully. 

如果下面的被編輯如下所述:

var fs = require("fs"); 
var async = require("async"); 
var buffer = new Buffer(10); 
var read = ""; 
var readByt; 
async.series([ 
    function(callback) { 
     console.log("test"); 
    }, 
    function (callback){ 
     console.log("console: 1"); 
    } 
    function (callback){ 
     console.log("console: 2"); 
    } 
],function(){}); 

輸出變化如下:

c:\>node fr.js 
test 

如何我是否獲得了async.seri中的所有功能? es執行?

+2

貌似你不調用'callback'功能讓'async.series'當每個函數完成知道。 – JohnnyHK

回答

2

我想你需要調用函數數組中提供的參數callback來指示async模塊調用下一個函數。

1
var fs = require("fs"); 
var async = require("async"); 
var buffer = new Buffer(10); 
var read = ""; 
var readByt; 
async.series([  
    function(callback) { 
     fs.open('c:/ab.txt', 'r+', function(err, fd) { 
      fs.read(fd, buffer, 0, buffer.length, 0, function(err, bytes){ 
       read = buffer.slice(0, bytes).toString(); 
       readByt = bytes;   
       console.log("}}}"+read); 
       fs.close(fd, function(err){ 
        if (err){ 
        console.log(err); 
        } 
        console.log("File closed successfully.");   
       }) 
      }) 
     }) 
 //invoke here for continue and to break use callback(false); 
    callback() 
}, 
    function (callback){ 
     console.log("console:"+read); 
     console.log("console:"+read.substr(read.length-1)); 
     console.log("console:"+buffer.slice(0, readByt).toString()); 
    } 
],function(){});