【问题标题】:How to retrieve value from callback?如何从回调中检索值?
【发布时间】:2014-02-04 21:12:01
【问题描述】:

如何从回调中获取值? 我需要首先按姓名查找学生,然后计算一些东西并返回结果。 按名称查找学生的函数返回错误并导致像

这样的回调
function findStudentAndCalculate(name, cb);

cb 是回调,它以参数 err 和学生实例为参数。 我通过了cb

function calculateSomething(err, st){
    if(err) throw new Error("Error")
    var result = some stuff with st;
    return result;
}

对于给定的带有名称参数的 url,我应该返回响应页面

findStudentAndCalculate("John", calculateSomething);

【问题讨论】:

  • 你没有。您在回调中使用 in 值。 findStudentAndCalculate 函数应该将数据传递到 cb
  • @cookiemonster 我有这些功能,不能改变,我需要这个执行链的返回结果。
  • 好吧,如果您无法更改它们,那么您将陷入困境。对不起。

标签: javascript node.js callback promise


【解决方案1】:

好吧,您还没有向我们提供足够的信息让findStudentAndCalculate 知道哪些值可用于回调参数,或者您希望如何存储或返回回调中的return 值,但是。 . .一般来说 。 . .当您将函数作为参数传入时,您只需将该函数视为已使用参数作为函数名称来定义它。因此,在您的情况下,在 findStudentAndCalculate 的某个时间点,您会拨打这样的电话:

var someVariable = cb(errValue, stValue);

。 . .或者 。 . .

return cb(errValue, stValue);

然后代码将像您直接调用一样:

var someVariable = calculateSomething(errValue, stValue);

。 . .或者 。 . .

return calculateSomething(errValue, stValue);

(分别)

【讨论】:

  • 这将假定findStudentAndCalculate() 是同步的。虽然有可能,但它会让人想知道为什么它会收到回调。
  • @cookiemonster - 我能想到原因。 . .如果有一大堆函数依赖学生信息,那么有人可能会设置一个以标准方式检索学生信息的函数,然后将其传递给下一个函数(名称实际上暗示了这一点)。我并不是说它是最佳方法,但是,在处理其他人的代码多年之后,我学会了不要过于拘泥于人们为什么选择一种方法而不是另一种方法。 :)
【解决方案2】:

这种回调模式最常用于asynchronous code。鉴于您将帖子标记为“nodejs”和“promise”,我将假设 findStudentAndCalculate 是异步的(例如,它必须在某处的数据库中查找学生,这需要时间),所以您不会可以直接用它的返回值做任何事情。

这里有两种可能:

  1. 如果findStudentAndCalculate 是一个典型的 Node.js 风格的异步函数(并且它确实看起来 像一个典型的函数),那么它不会返回任何有用的东西。相反,您需要在您提供的回调函数中完成所有工作(即在calculateSomething 本身内部)。换句话说,您不仅需要calculateSmething,还需要calculateSomethingAndThenDoSomethingWithWhatYouCalculated)。

  2. 另一方面,如果findStudentAndCalculate 返回promise,您可以使用它的then 方法“对您计算的内容做一些事情”。这将允许您将用于计算的代码与使用该计算的代码分开。例如:

    findStudentAndCalculate(name, calculateSomething).then(function (result) {
      // do something with result
    })
    

    不过,这将是一种非常不寻常构建承诺的方式。通常,模式看起来更像这样:

    findStudent(name).then(calculateSomething).then(function (result) {
      // do something with result
    })
    

不过,正如 talemyn 所说,我们确实需要更多关于 findStudentAndCalculate 的信息,然后才能更具体。

【讨论】:

    猜你喜欢
    • 2017-04-23
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 2023-03-18
    • 2014-09-10
    • 2018-04-14
    相关资源
    最近更新 更多