本文介绍了在JavaScript中的函数范围之外返回变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了此处发布的所有解决方案,但没有任何效果,因为我的问题有所不同.

I tried all the solutions posted here, but nothing worked, because my problem is a bit different.

我有以下代码(从外部neo4j模块调用代码以将节点插入Neo4J数据库,然后获取该节点的Neo4J ID)

I have the following code (calls on a code from external neo4j module to insert a node into Neo4J database and then gets the Neo4J Id of that node):

dbneo.insertNode({
    auth_id: user.id,
    username: user.name,
    name: user.name
},function (err, node){
    if(err) throw err;
    // Output node properties.
    console.log(node.data);
    // Output node id.
    console.log(node.id);
});

一切正常,但是如何在功能范围(err,node)之外传递 node.id ,然后将该值添加到另一个对象中?

All works fine, but how do I deliver node.id outside of the scope of function (err,node) to then add this value to another object?

当我尝试做类似的事情

user.neo_id = node.id;

在上面的代码段之后,它是未定义的(当然).

after that block of the code above, it's undefined (of course).

试图在命名函数中运行dbneo.insertNode,但是如果我将返回值放入函数(err,node)中,则仍然是未定义的.

Tried to run the dbneo.insertNode inside a named function, but if I put the return value into function (err, node) it's undefined anyway.

很抱歉,这个问题有点简单/愚蠢,但我只是从JavaScript开始.谢谢!

Sorry if the question is a bit simple/stupid, but I'm just starting in JavaScript. Thank you!

推荐答案

好的,因此,在您提出建议后,我获得了此临时代码.可能不是最好的(可能会阻塞),但是它可以解决问题.

Ok, so after your advice, I have this interim code. Probably not the best (may clog), but it resolves the problem.

仅在确定我从Neo4J数据库接收到变量(node.id)之后,我才简单地调用下一个函数.如果有人知道更优雅的解决方案,请告诉我(尤其是异步库).

I simply call for the next function only after I'm sure I received the variable (node.id) from Neo4J database. If anyone knows a more elegant solution, please, do let me know (especially with async library).

 dbneo.insertNode({
    auth_id: user.id,
    username: user.name,
    name: user.name
},function (err, node){
    if(err) throw err;
    // Output node properties.
    console.log(node.data);
    // Output node id.
    console.log(node.id);

    // RECEIVED node.id ? ONLY THEN SEND IT TO THE FUNCTION THAT NEEDS IT
    send_neo_id(node.id);
});


// THIS IS THE FUNCTION THAT WAS NOT RECEIVING NODE.ID BEFORE:

function send_neo_id(neo_id) {
    user.neo_id = neo_id;
    db.set('user:id:' + user.name, id, function(err) {
        if (err) return fn(err);
        db.hmset('user:' + id, user, function(err) {
            fn(err);
        });
    });
};

这篇关于在JavaScript中的函数范围之外返回变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 22:28