什么是属性“完成"?在 NodeJS 中? [英] What is the attribute "done" in NodeJS?

查看:40
本文介绍了什么是属性“完成"?在 NodeJS 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照本教程在 NodeJS 中编写本地登录代码:

I'm coding the local login in NodeJS following this tutorial:

https://scotch.io/tutorials/easy-node-身份验证设置和本地

在文件 config/passport.js 中

In the file config/passport.js

function(req, email, password, done){
    process.nextTick(function(){
        User.findOne({'local.email' :   email}, function(err, user){
            if(err)
                return done(err);
            if (user){
                return done(null, false, req.flash('signupMessage', 'message'));
            }

我是 NodeJS 和 Javascript 的新手,我不明白像done"这样的值如何成为一个函数(返回 done(err)).有什么系统功能吗?

I'm rookie in NodeJS and Javascript, and I don't understand how a value like "done" can be a function (return done(err)). Is any system function?

非常感谢!

推荐答案

done 是您完成工作后需要调用的回调.如您所见,它在代码的第一行中给出:

done is a callback that you need to call once you are done with your work. As you can see it is given in the first line of your code:

function(req, email, password, done){

这意味着除了传入的请求之外,您还可以获得用户指定的emailpassword.现在你需要做任何你需要做的事情来验证登录.你需要以某种方式告诉 Passport 你成功与否.

This means that besides the incoming request you get the user-specified email and password. Now you need to do whatever you need to do to verify the login. Somehow you need to tell Passport whether you succeeded or not.

通常,您可以为此使用返回值,但在这种情况下,Passport 作者考虑了您的支票可能是异步的选项,因此使用返回值不起作用.

Normally, you may use a return value for this, but in this case the Passport author thought about the option that your check may be asynchronous, hence using a return value would not work.

这就是使用回调的原因.大多数情况下回调被称为 callback,但这只是为了方便,没有技术上的理由这样做.在这种情况下,由于回调用于显示您完成,Passport 作者建议将其称为 done.

This is why a callback is being used. Most often callbacks are being called callback, but this is just for convenience, there is no technical reason to do so. In this case, since the callback is being used for showing that you are done, the Passport author suggested to call it done.

现在,如果凭据验证失败,您可以调用 done 并显示错误,或者使用适当的参数来表明验证成功.

Now you can either call done with an error if credential validation failed, or with the appropriate parameters to show that it succeeded.

这是可行的,因为函数在 JavaScript 中是所谓的一等公民,即代码和数据之间没有实际区别:在 JavaScript 中,您可以将函数作为参数传递并返回值可以用数据.

This works because functions are so-called first-class citizens in JavaScript, i.e. there is no actual difference between code and data: In JavaScript you can pass functions around as parameters and return values as you can with data.

就是这样:-)

这篇关于什么是属性“完成"?在 NodeJS 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆