嵌套异步未按预期执行

时间:2016-08-23 13:22:32

标签: javascript node.js async.js

我是节点js的新手,我正在尝试使用异步模块来消除setTimeouts。我在这里遇到了一个问题。它没有按预期工作。它甚至在第一个函数完成执行之前调用第二个函数。我搜索了答案并尝试了多种方法。但它似乎没有用。它甚至在async.forEach完成之前就打印出“异步系列中的内部数据库插入”。任何人都可以检查代码并告诉我哪里出错了?

setTimeout(function() {
    async.series([function(callback1) {
                console.log("Inside async series");
                try {
                    var msg = "";
                    var datas = [];
                    for (var i = 0; i < service_name.length; i++) {
                        console.log("Inside for loop service names");
                        var child = {
                            "space_guid": space_guid,
                            "name": service_name[i],
                            "service_plan_guid": service_plan_guid[i]
                        };
                        datas.push(child);
                        console.log("datas array===" + JSON.stringify(datas))
                    }
                    async.forEach(datas, function(data1, callback) {

                        console.log("Inside async task");
                        var data = JSON.stringify(data1);
                        console.log("data value===" + JSON.stringify(data));
                        var options = {
                            host: 'api.ng.bluemix.net',
                            path: '/v2/service_instances' +
                                '?accepts_incomplete=true',
                            method: 'POST',
                            headers: {
                                'Authorization': full_token_new
                            }

                        };
                        console.log("options is" + JSON.stringify(options));
                        var reqst = http.request(options, function(res) {
                            console.log("Sent for request");
                            res.setEncoding('utf8');
                            res.on('data', function(chunk) {
                                msg += chunk;

                            });
                            res.on('end', function() {
                                try {
                                    console.log("message =======", msg);
                                    console.log("-----------------------------------------");
                                    msg = JSON.stringify(msg);
                                    msg1 = JSON.parse(msg);
                                    console.log("printing msg--" + msg1);
                                    console.log("-----------------------------------------");
                                    console.log("here i am", i);
                                    console.log(service_name.length - 1);
                                    callback();

                                } catch (err) {
                                    console.log(err);
                                }

                            });
                        });
                        reqst.on('error', function(e) {
                            console.log(e);
                        });
                        reqst.write(data);
                        reqst.end();

                    }, function(err) {

                        console.log("for each error" + err);


                    });
                    callback1(null, null);
                } catch (err) {
                    console.log(err);
                }

            },
            function(callback1) {
                console.log("Inside db insert in async series")
                db_insert(service_name, solnName, full_token_new, uname, version);
                callback1(null, null);

            }
        ],
        function(err, results) {
            if (err) {
                console.log("There's an error" + err);
            } else {
                console.log("result of async", results);
            }
        })
}, 3000)

2 个答案:

答案 0 :(得分:0)

您正在将try...catch与异步代码混合,这是不好的做法,几乎不可能做得对。

此外,您的错误源于您在callback之后调用async.forEach这一事实,但未完成,请转到下一步。

另外,“消除超时”是什么意思?您的整个代码都在其中,您可以随时删除它。

'use strict';

async.series([
    (callback) => {
        let msg = "",
            datas = [],
            i = 0;
        while(i < service_name.length) {
            let child = {
                "space_guid": space_guid,
                "name": service_name[i],
                "service_plan_guid": service_plan_guid[i]
            };
            datas.push(child);
            i = i + 1;
        }
        async.forEach(datas, (data1, callback) => {
            let data = JSON.stringify(data1),
                options = {
                    host: 'api.ng.bluemix.net',
                    path: '/v2/service_instances?accepts_incomplete=true',
                    method: 'POST',
                    headers: {
                        'Authorization': full_token_new
                    }
                },
                reqst = http.request(options, (res) => {
                    res.setEncoding('utf8');
                    res.on('data', (chunk) => {
                        msg += chunk;
                    });
                    res.on('end', () => {
                        msg = JSON.stringify(msg);
                        msg1 = JSON.parse(msg);
                        callback();
                    });
                });
            reqst.on('error', (error) => {
                callback(error);
            });
            reqst.write(data);
            reqst.end();
        }, (error) => {
            callback(error);
        });
    },
    (callback) => {
        db_insert(service_name, solnName, full_token_new, uname, version);
        callback();
    }
],
(error, results) => {
    if (error) {
        console.log("There's an error" + error);
    } else {
        console.log("result of async", results);
    }
});

由于这种气味非常类似于plssendzecode问题,因此我删除了每个console.log并删除了ES6,以确保您无法使用它,并且需要阅读我所做的更改

答案 1 :(得分:0)

我简化了一些代码。
datasprocessData并不是好名字。

setTimeout(onTimer, 3000);

function onTimer() {
    var datas = service_name.map(function(name, i) {
        return {
            space_guid: space_guid,
            name: name,
            service_plan_guid: service_plan_guid[i]
        }
    });

    function processData(data, callback) {
        var options = {
            host: 'api.ng.bluemix.net',
            path: '/v2/service_instances?accepts_incomplete=true',
            method: 'POST',
            headers: {
                'Authorization': full_token_new
            }
        };

        var reqst = http.request(options, function(res) {
            var msg = '';
            res.setEncoding('utf8');

            res.on('data', function(chunk) {
                msg += chunk;
            });

            res.on('end', function() {
                try {
                    msg = JSON.parse(msg);
                    callback(null, msg);
                } catch (err) {
                    callback(err);
                }
            });
        });

        reqst.on('error', callback);
        reqst.write(JSON.stringify(data));
        reqst.end();
    }

    async.map(datas, processData, function(err, results) {
        if (err);
            return console.log(err);
        // process msg of each request db_insert(...);  
    });
};