简体   繁体   中英

Node Async with functions

I'm trying to use Async module with 2 functions, here is the code. There's something wrong, the console.dir are working, but the last one in function(err, results) doesn't work. Can any one help me?

The last step that I want to do is render the oftArrayFullInfo and oftNextInfo

async.parallel({
        one: function(callback){
            auxFunctions.foofunc1(foo1, foo1, function(oftArrayFullInfo){
                console.log("****** ASYNC 1 ARRAY");
                console.dir(oftArrayFullInfo);
                callback(oftArrayFullInfo);
            });
        },
        two: function(callback){
            auxFunctions.foofunc2(foo1, foo1, function(oftNextInfo){
                console.log("****** ASYNC 2 ARRAY");
                console.dir(oftNextInfo);
                callback(oftNextInfo);
            });
        }
    },
    function(err, results){
        console.log("****** RENDER 1");
        console.dir(results.one);
        console.log("****** RENDER 2")
        console.dir(results.two);
        //res.render('myView', {title: 'Job Info', oftArrayFullInfo}, {title: 'Next Jobs Info', oftNextInfo});
    });

Your main issue is that you're not calling the callbacks correctly.

async callbacks, and asynchronous callbacks in Node.js in general, take two arguments: the first one is used to pass any errors (or null if there aren't any), the second one is used to pass the result.

You are calling them with only the first argument:

callback(oftArrayFullInfo);

This will make async think that the function has failed, which will cause results in the final callback to be undefined. When you subsequently try to access results.one , an error will be thrown.

To fix this, you should call the callbacks properly:

callback(null, oftArrayFullInfo)
callback(null, oftNextInfo)

And, as suggested already, you should uncomment the res.render() .

Eventually, you should also make your auxilliary functions ( auxFunctions.foofunc1 and auxFunctions.foofunc2 ) adhere to the same calling convention.

ok you did everything right except when u send data from re.render() to your templates you have to send in key,value pairs.so intead

res.render('myView', {title: 'Job Info', oftArrayFullInfo}, {title: 'Next Jobs Info', oftNextInfo});

you should use

res.render('myView', {title: 'Job Info', arrayFullInfo : oftArrayFullInfo}, {title: 'Next Jobs Info', nextInfo : oftNextInfo});

now you can access these values with the key names arrayFullInfo and nextInfo in your template

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