首页 > 解决方案 > 在nodejs中同步For循环?

问题描述

这是我的代码

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 循环,但我无法获得正确的值。i 的值在 if 块中没有递增inner_result

标签: node.js

解决方案


用下面的代码替换你的 for 循环:

// 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
})

推荐阅读