且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Node.js:无法从同一文件中的其他函数返回值

更新时间:2022-12-20 14:39:12

虽然我同意这是一个基本的异步问题,上面提到的链接以非常一般的方式回答它,并且坦率地说这个问题是TLDR。

Although I agree that this is a basic Async issue, the link prescribed above answers it in a very general way, and is frankly TLDR for this issue here.

因为你的进程,比如save,是异步的,你不能只是回来的东西。相反,将闭包/函数传递给代码,并在事情完成后调用该函数。大多数Node都是以这种用法为基础的,原因是这里列出了TLDR。

Since your processes, like save, are asynchronous, you can't just return something back. Instead, pass a closure / function to the code, and call that function when things have completed. Most of Node is predicated on this kind of usage, for reasons that are TLDR to list here.

createNewUser(req.body,null,function(result){
    if (!result.success){
            res.status(500).json({
                message: "unable to create User",
                obj: result.err
            })
        } else {
            res.status(200).json({
                message: "successfully created new user",
                obj: result.obj
            })
        }
});

function createNewUser(userData, socialRegistry, onComplete){
 ....
    user.save(function(err, user) {
        if (err) {
            onComplete({
                success: false,
                err: err
            })
        }
        if (socialRegistry){
            onComplete(user)
        } else {
            onComplete({
                success: true,
                obj: user
            })
        }
    });
}

有一些对后代很有帮助的答案,这可能不是他们,但简单有力量。

There are some answers that are great for posterity, this may not be one of them, but there is power in simplicity.

哦,回答你在帖子中发布的一个问题, 'result'永远不会被设置为任何东西的原因是你的函数已经完成并且在异步调用user.save()之后有一个隐式返回。

Oh, and to answer one of the questions you post in your post, the reason why 'result' never gets set to anything is that your function has already completed and has an implicit return after the async call to user.save().