在 node js module.exports 中创建回调

Cha*_*aHS 1 javascript node.js

如何在 module.exports 参数中创建回调函数。我正在尝试做如下类似的事情,我想知道如何实现回调函数。

模块.js

module.exports = (a, b, callback) => {
  let sum = a+b
  let error = null
  //callback
}
Run Code Online (Sandbox Code Playgroud)

应用程序.js

const add = require(./module.js)

  add(1,2, (err, result) => {

  }
Run Code Online (Sandbox Code Playgroud)

Shu*_*uki 6

在您的 module.exports 中,您需要“调用”回调函数。像这样

callback(error, sum)
Run Code Online (Sandbox Code Playgroud)

这会将控制权返回给 app.jsadd()函数。你在这里实现你的回调函数。即你想对你收到的结果做什么。

这是您的代码的样子:-

模块.js

    module.exports = (a, b, callback) => {
      let sum = a+b
      let error = null
      callback(error, sum) // invoke the callback function
    }
Run Code Online (Sandbox Code Playgroud)

应用程序.js

    const add = require("./module")

    add(1,2, (err, result) => {
      if(err) { // Best practice to handle your errors
          console.log(err)
      } else { // Implement the logic, what you want to do once you recieve the response back 
        console.log(result) 
      }
    })
Run Code Online (Sandbox Code Playgroud)