大多数 npm 包总是在它们的页面中使用“完成”回调函数。我很难理解它。例如:
passport.serializeUser(function(user, done) {
done(null, user.id);
});
这是我的理解:
“done”是一个回调函数,所以它的任务是保存“null”和“user.id”的结果。如果是这样,持有“null”的意义何在?我们不能直接说 done(user.id)
吗?
如果我的理解有误,上面代码的解释是什么?
此外,该代码是用旧的 javascript 编写的。我们如何使用带有箭头函数的现代 javascript 编写它,或者如果可能的话使用 async/await 编写它?
我尝试用 async/await 来写。这是正确的吗?
passport.serializeUser(async (user)=>{
return await user.id})
最佳答案
passport.serializeUser(function(user, done) {
done(null, user.id);
});
和
一样passport.serializeUser(function(user, callback) {
callback(null, user.id);
});
In node.js, it is considered standard practice to handle errors in asynchronous functions by returning them as the first argument to the current function's callback. If there is an error, the first parameter is passed an Error object with all the details. Otherwise, the first parameter is null.
因此,done 的第一个参数可能是错误的,第二个是实际值
关于javascript - Node.js 中的 "done"回调函数是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56553599/