Wednesday, 3 May 2017

nodejs: Async.series only executes the first function and stops

On executing the following code, only first function of the async.series executes.

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

The output is given below:

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

If the following is edited as mentioned below:

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

The output changes as below:

c:\>node fr.js
test

How do i get all the functions in the async.series to execute?



via ManFriday

No comments:

Post a Comment