简体   繁体   中英

NodeJs waterfall callback functionality is not working

I am using npm async waterfall method to write a functionality. There I found a strange situation(May be, My awareness is low). My function is as follows. I create an array of events in the first function and pass it to the second function via the callback parameters. Then I capture that array in the second function and loop it. I want to manipulate several values of the array. After that I send it to the final function.

The console.log statement in final function is only outputting the initial state of array from first function and not the manipulations that I have done in second function. Any idea is highly appreciated.

var _async = require('async');
var criteria =  {};

_async.waterfall([
    function getSortedCalenderItems(callback){
        var events = []; // set of events are included inthis array
        callback(null, events)
    },

    function getUsers(events, callback) {  
            for (var i = 0; i < events.length; i++) {
                var event = events[i];
                var user = event.shared_user;

                // manipulate user
                var newUser = {
                    'id' : '<id>',
                    'name' : 'New name'
                };

                event.shared_user = newUser;
                events[i-1] = event;

                if(i === (events.length)) {
                    callback(null, events)
                }
            }

    }
],function(err, events){
        console.log(events); // this shows the initial state of the array. Not the manipulated events array.
        return;
});

For example;

var _async = require('async');
var criteria = {};

_async.waterfall([
    function (callback) {
        var events = [// set of events are included inthis array
            {
                name: "event1",
                shared_user : "halil"
            }, {
                name: "event1",
                shared_user : "halil"
            }
        ];
        callback(null, events);
    },
    function (events, callback) {
        console.log(events)
        for (var i = 0; i < events.length; i++) {
            var event = events[i];
            var user = event.shared_user;

            // manipulate user
            user = {
                'id': '<id>',
                'name': 'New name'
            };

            if (i === (events.length - 1)) {
                callback({}, events)
            }
        }
    }
], function (err, events) {
    console.log(err, events);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM