【问题标题】:How to Return Value in Pass-Through Function (Node.js)如何在传递函数(Node.js)中返回值
【发布时间】:2018-08-08 22:56:54
【问题描述】:

我正在尝试将父函数中的变量设置为 Node 中的导入和嵌套函数。

家长

const child = require('./child')

function init() {
  second()
  let def = abc
  console.log(def) // Expected log: 15
                   // Actual log: abc is not defined
}

function second() {
  return child.third()
}

init()

儿童

exports.third = () => {
  let abc = 15
  return abc
}

如何正确返回abc的值,以便可以设置并登录init()

【问题讨论】:

  • 你为什么不在你的 init() 块中简单地做 abc = second() 呢?我错过了什么吗?
  • 不。这样可行。谢谢!!

标签: node.js callback promise


【解决方案1】:

只需在 init() 块中执行 abc = second()

【讨论】:

    【解决方案2】:

    也许我不明白您的问题,但为了包含您需要的任何内容,请先将其导出。

    function third() {
      let abc = 15
      return abc
    }
    module.exports = {
        third
    };
    

    现在,你只需要导入文件并调用函数

    const child = require('child')
    
    function init() {
      let def = second();
      console.log(def) // Expected log: 15
    }
    
    function second() {
      return child.third()
    }
    
    init()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      相关资源
      最近更新 更多