【问题标题】:nested Async not executing as expected嵌套异步未按预期执行
【发布时间】:2016-08-23 22:04:24
【问题描述】:

我是 node js 的新手,我正在尝试使用异步模块来消除 setTimeouts。在这里我面临一个问题。它没有按预期工作。它甚至在第一个函数完成执行之前调用第二个函数。我搜索了答案并尝试了多种方法。但这似乎不起作用。它甚至在 async.forEach 完成之前打印“Inside db insert in async series”。谁能检查代码并告诉我哪里出错了?

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)

【问题讨论】:

  • 不要将try...catch 与异步函数混用,它不会像你期望的那样工作。
  • try 块中取callback1(null, null); 并将其放在async.forEach 的最后一个函数中,就在console.log("for each error" + err);
  • 使用async.each 代替async.forEach

标签: javascript node.js async.js


【解决方案1】:

您将try...catch 与异步代码混合在一起,这是一种不好的做法,几乎不可能做到正确。

另外,您的错误源于您在async.forEach 之后调用callback,这没有完成,请转到下一步。

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

'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 以确保您将无法使用它并需要阅读我所做的更改。

【讨论】:

  • 我的意思是我已经通过使用异步消除了许多设置超时。我还删除了try catch并将callback1放在function(err)中。还是不行:(
【解决方案2】:

我稍微简化了代码。
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(...);  
    });
};  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 2019-04-09
    • 1970-01-01
    相关资源
    最近更新 更多