nodejs:async.series不按顺序执行函数

时间:2017-05-04 05:01:47

标签: javascript node.js

在以下代码中,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.

如何按顺序执行这些操作?

1 个答案:

答案 0 :(得分: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(){});