【问题标题】:How to use callback functions in node js如何在节点js中使用回调函数
【发布时间】:2018-02-18 02:13:02
【问题描述】:

我必须从函数B调用函数A

function A() {
  // File read etc functionality goes here//
  return data;
}

function B() {
  var result = A(); 
}

由于异步,我的结果 var 为空,即使函数 A 返回数据。谁能帮助我。谢谢。

【问题讨论】:

标签: javascript node.js asynchronous synchronization mean-stack


【解决方案1】:

您的示例不正确。提供的代码中没有异步。并且在 B 中调用函数 A 不需要再次编写函数,只需编写 A(),就可以得到结果。要获得异步结果,您应该更改编码方法。

如果您不希望某些结果是异步的,则应考虑使用承诺或回调。

喜欢这里:

//cb will be callback function that is provded by the caller code
//in this example it is a anonymouse function from B
function A(cb) {
  // File read etc functionality goes here//
  //this callback should be called when data is ready
  cb(data);
}

function B() {
  A(function (data) {
    //do with data what you want here
  });
}

【讨论】:

  • 当我对我得到的数据进行控制台时,但当我控制台结果时,我却是空的。
猜你喜欢
  • 2018-07-15
  • 1970-01-01
  • 2021-08-21
  • 2018-03-28
  • 2017-08-27
  • 2023-03-23
  • 1970-01-01
  • 2018-10-06
  • 1970-01-01
相关资源
最近更新 更多