javascript - Node.js 中的 "done"回调函数是什么?

标签 javascript node.js callback async-await

大多数 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 的第一个参数可能是错误的,第二个是实际值

docs

关于javascript - Node.js 中的 "done"回调函数是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56553599/

相关文章:

php - fabric js 或 imagick 从图像中删除白色

javascript - SVG 嵌入到 HTML 中,拖放代码问题

javascript - 根据视口(viewport)宽度更改 fullCalendar View 和标题选项?

node.js - npm 安装redis 问题

javascript - 如何在 sails.js 0.10 中接收套接字事件?

c++ - 在回调中传递数据

javascript - jquery 搜索表格单元格 -> 更新相邻单元格

c - 理解 libuv/epoll/非阻塞网络 IO

javascript - 我怎样才能让 `.then()` 保持足够长的时间以实现具有 native promise 的轮询功能?

javascript - react setState : Callback to function of child-component