在Node.js中同步循环?

时间:2018-09-06 16:47:10

标签: node.js

这是我的代码

function getallCollections(cb) {
    var query = "select id,name from categories where parent_id is NULL LIMIT 4";

    var collection_menu = [];

    con.query(query, (err, result) => {
        if (result) { // get result
            flag = 0;
            for (i = 0; i < result.length; i++) {

                var inner_query = "select * from categories where parent_id = " + result[i].id + " LIMIT 6";

                con.query(inner_query, function(err, inner_result) {
                    if (inner_result) { //get new result
                        console.log(result[i].name)
                        flag++;
                        inner_result.parent_name = result[i].name // producing value of result[0].name in each loop
                        collection_menu.push(inner_result)
                        if (flag === 4) {
                            cb(collection_menu)
                        }
                    } else {
                        console.log(err)
                    }
                })
            }

        }
    })
}

此处inner_result.parent_name的值始终相同。我知道这是因为异步for循环,但是我无法获得正确的值。 inner_result的if块中i的值没有增加。

1 个答案:

答案 0 :(得分:1)

用以下代码替换循环:

// try know about async library 
async.map(result, function(each, next) {
    //better way -- select the data you required to process so that you don't need the flag
    var inner_query = "select * from categories where parent_id = " + each.id + " LIMIT 6";

    con.query(inner_query, function(err, inner_result) {
        if (inner_result) { //get new result
            inner_result = JSON.parse(JSON.stringify(inner_result));
            console.log(each.name);
            flag++;
            inner_result.parent_name = each.name; // producing value of result[0].name in each loop
            collection_menu.push(inner_result);
            if (flag === 4) {
                //try to avoid flag | but here is how you can break
                next(true);
            } else {
                next();
            }
        } else {
            console.log(err)
            next();
        }
    });
}, function(error, result) {
    if (error == true) {
        // your noraml flow after flag == 4
        cb(collection_menu);
    } else {
        // your code
    }

    // hope this work | minor changes may require
})