0

在 CoffeeScript 的 Node/Express 服务器中,我有以下功能:

@resolveServers = (url, servers, answer) ->
  result = []
  treatServer(url, server, (treatAnswer) ->
    result.push(treatAnswer)
  ) for server in servers
  answer(result)

treatServer 方法需要一些时间,并且在循环完成之前发送答案。仅当循环结束时如何发送结果?

谢谢您的帮助。

4

2 回答 2

2

只要您事先知道服务器的数量,这很容易:

@resolveServers = (url, servers, answer) ->
    result = []
    count = 0
    treatServer(url, server, (treatAnswer) ->
        result.push(treatAnswer)
        count++
        answer result if count is servers.length
    ) for server in servers

编辑:再次考虑之后。在您的情况下,这可以更容易地解决:

@resolveServers = (url, servers, answer) ->
    result = []
    treatServer(url, server, (treatAnswer) ->
        result.push treatAnswer
        answer result if result.length is servers.length
    ) for server in servers

编辑 2:正如斜眼所指出的, push 返回数组的长度:

@resolveServers = (url, servers, answer) ->
    result = []
    treatServer(url, server, (treatAnswer) ->
        answer result if result.push(treatAnswer) is servers.length
    ) for server in servers

如果您想保持代码的可读性,最后一次编辑可能不是最佳选择;-)

于 2013-05-15T16:43:41.727 回答
0

您还可以使用异步模块

这是一篇很棒的文章Node.js async in practice:When to use what?其中详细解释了异步。

于 2013-05-16T15:47:17.943 回答