node.js:等待所有线程完成

时间:2015-07-15 09:45:39

标签: node.js multithreading coffeescript hubot slack-api

我在coffeescript中编写了一个hubot脚本。该脚本打开三个线程,这些线程都执行YQL查询。如果每个线程将他的消息发送到聊天客户端(在我的情况下为Slack)client dies。现在我需要以某种方式从所有线程中收集字符串并将它们组合在一个发送命令中,我该如何做到最好?

slack_message = '*Todays menu*'
for i in [1..3]
  query = "select * from html where url='XPATH.. ["+i+"] XPATH.."
  new YQL.exec query, (response) ->
    m = response.query.results;
    slack_message += m

msg.send slack_message

1 个答案:

答案 0 :(得分:1)

你可以随时保留一个柜台:

slack_message = '*Todays menu*'
queries_done = 0

for i in [1..3]
  query = "select * from html where url='XPATH.. ["+i+"] XPATH.."
  new YQL.exec query, (response) ->
    m = response.query.results
    slack_message += m

    if queries_done is 3
      msg.send slack_message

您也可以使用Promises

Promise = require("promise")

call_query = (query) ->
  new Promise (resolve) ->
    new YQL.exec query, (response) ->
      resolve response.query.results;

get_menu = ->
  slack_message = '*Todays menu*'
  queries = []
  for i in [1..3]
    queries.push (call_query "select * from html where url='XPATH.. ["+i+"] XPATH..")

  Promise.all(queries).then (messages) ->
    msg.send slack_message + messages.join()

Promise是异步逻辑回调的替代方法,你可以像Promise.all那样用它们来做很好的事情,这正是你正在寻找的。它接收一组Promise个对象,当它们全部被解析时,它继续执行.then。如果你有一个晚上,我建议你阅读一下。一旦你掌握了它们的工作方式,它们就可以使事情变得更好。