小白请教一个函数调用问题,异步不太懂
发布于 8 年前 作者 yjg159 2911 次浏览 来自 问答
var getChild = function(rootName) {

    var cypher = "Match (n:Country {name:'" + rootName + "'})-[:children]->(m) return m";

    db.cypherQuery(cypher, function(err, result) {
        if (err) throw err;
        return result;
    });
}

var initJson = function(rootName, parent) {
    var result = getChild(rootName);

    if (result.data.length != 0) {
        //TODO
        var children = [];
        for (var i = 0; i < result.data.length; i++) {
            children[i] = { name: result.data[i].name };
            initJson(result.data[i].name, children[i]);
        }
        parent.children = children;
        return;
    } else {
        //TODO
        return;
    }
}
var createJson = function(rootName) {
    json.name = rootName;
    var parent = json;
    initJson(rootName, parent);
    console.log(JSON.stringify(json));
}
router.get('/', function(req, res) {
    function_one();
    res.render('index', { title: "Express" });
});

在initJson调用getChild的时候得到的返回都是undefined,我知道在getchild里面没返回出来,但是现在也没找到合适的办法,希望能有人能帮我解答一下,谢谢。

3 回复
var getChild = function(rootName,callback) {

    var cypher = "Match (n:Country {name:'" + rootName + "'})-[:children]->(m) return m";

    db.cypherQuery(cypher, function(err, result) {
        if (err) throw err;
        return callback(null,result);
    });
}
var initJson = function(rootName, parent) {
   	getChild(rootName,function(err,result{
	if(err) throw err;
		if (result.data.length != 0) {
			//TODO
			var children = [];
			for (var i = 0; i < result.data.length; i++) {
				children[i] = { name: result.data[i].name };
				initJson(result.data[i].name, children[i]);
			}
			parent.children = children;
			return;
		} else {
			//TODO
			return;
		}
	}));
}

谢谢! 十分感谢!

@jiangli373 十分感谢!

回到顶部