【问题标题】:Returning a callback for centralized handling返回集中处理的回调
【发布时间】:2014-11-26 07:06:24
【问题描述】:

在fileA中,我可以做

@someAPI = SomeAPI()
@someAPI.getUser '123'

然后在文件B中

class SomeAPI

  constructor: (options = {}) ->
    unless @ instanceof SomeAPI
      return new SomeAPI(options)

  getUser: (id) ->
    someAPI.get 'users/show', { 'id': id }, (err, data, res) ->
      if data
        console.log data.name

但是有什么方法可以返回回调,所以我可以在 fileA 中进行处理吗?

fileA 伪代码

...

processUser: (id) ->
  @someAPI.getUser id, (err, data, res) ->
    if data
      console.log data.name

processUser '123'

fileB 伪代码

...

getUser: (id) ->
  return someAPI.get 'users/show', { 'id': id }, (err, data, res)

这适用于 Meteor 应用,其中 fileA 是应用的一部分,fileB 是包的一部分。

【问题讨论】:

  • 这是在客户端还是服务器上?

标签: javascript meteor coffeescript


【解决方案1】:

你为什么不反过来想,把回调传给 fileB 呢?

getUser: (id, callback) ->
  return someAPI.get 'users/show', { 'id': id }, callback

然后在您的应用代码中,将回调作为参数传递以在本地执行结果处理:

processUser: (id) ->
  @someAPI.getUser id, (err, data, res) ->
    if data
      console.log data name

这就是你所做的,所以我不确定我是否理解你的担忧。

【讨论】:

  • 谢谢,效果很好。一般来说,我是回调的新手,所以缺少一些基础知识。 ^^
  • 除非回调结构不同怎么办? IE。如果我必须在返回之前对 getUser 方法进行一些修改。
  • getUser 只是一些 api 调用的包装器,它只接受参数和回调,所以我不确定你可以在 getUser 中合理地做哪些修补,这不会最好发生在之前在 api 调用者上下文中对getUser 的调用...如果您想从我这里得到更好的答案,请用一个清晰​​的例子编辑您的问题。
  • 我会用一个清晰​​的例子提出一个新问题,因为我认为您的回答涵盖了我最初询问的内容。
【解决方案2】:

由于您在服务器上,因此您可以使用纤程以同步方式编写它。例如,使用期货:

# fileB
Future = Npm.require("fibers/future")

class SomeAPI
  constructor: # ...
  getUser: (id) ->
    # Create a Future object
    fut = new Future()

    # Fire off an API call; when it finishes we store the result in
    # the Future object
    someAPI.get 'users/show', { 'id': id }, (err, data, res) ->
      if err
        fut.throw(err)
      else
        fut.return([data, res])

    # Wait for the Future to resolve and return the value we stored in it
    return fut.wait()

# Usage in fileA
# This is synchronous. If an error occurred, you will get an exception
[data, res] = @someApi.getUser(id)
console.log(data.name)

如果您想在 Meteor 方法中调用 API,您可能必须使用 Fiber。

【讨论】:

    猜你喜欢
    • 2012-11-25
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多