2017-05-04 108 views
0

在以下代碼中,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("test"); 
     callback(); 
    }, 
    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.");   
       }) 
      }) 
     }) 
     callback(); 
    }, 
    function (callback){ 
     console.log("console:"+read); 
     console.log("console:"+read.substr(read.length-1)); 
     console.log("console:"+buffer.slice(0, readByt).toString()); 
     callback(); 
    } 
],function(){}); 

在通過命令行執行時,第三個塊中的緩衝區打印發生在文件讀取操作之前。

c:\>node fr.js 
test 
console: 
console: 
console: ?F  p? 
}}}c:/log.txt 
File closed successfully. 

如何讓這些按順序執行?

+0

的可能的複製[Node.js的async.series是,它是如何工作的?](http://stackoverflow.com/questions/15969082/node-js-async-series-is-that如何工作) – John

回答

1

您的回調將在每個異步功能完成後調用。在你的情況下,FS的行動是異步的,並在後期完成。在fs動作完成之前,回調將被調用。

試試這個,調用fs.close中的回調函數。

var fs = require("fs"); 
var async = require("async"); 
var buffer = new Buffer(10); 
var read = ""; 
var readByt; 
async.series([ 
    function(callback) { 
     console.log("test"); 
     callback(); 
    }, 
    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."); 
        callback();   
       }) 
      }) 
     }) 
    }, 
    function (callback){ 
     console.log("console:"+read); 
     console.log("console:"+read.substr(read.length-1)); 
     console.log("console:"+buffer.slice(0, readByt).toString()); 
     callback(); 
    } 
],function(){}); 
+0

謝謝@undefined - 非常明確的答案 - 完美的作品 – BabyGroot