意外的回调执行顺序

时间:2015-12-01 17:04:03

标签: node.js coffeescript hubot

我正在编写一个hubot脚本,按地区列出我在AWS中的所有CloudFormation堆栈。我写了以下内容,除了数据输出的顺序外,它都有效。脚本是:

key = process.env.HUBOT_AWS_ACCESS_KEY_ID
secret = process.env.HUBOT_AWS_SECRET_ACCESS_KEY
defaultRegions = 'us-east-1,us-west-2,eu-west-1'

_ = require 'underscore'
moment = require 'moment'
AWS = require 'aws-sdk'

getRegionStacks = (region, logger, msg) ->
    msg.send "In region #{region}:"
    AWS.config.region = region
    cloudFormation = new AWS.CloudFormation()
    params = {
        StackStatusFilter: [ 'CREATE_COMPLETE' ]
    }
    cloudFormation.listStacks params, (err, data) ->
        if err
            logger.error "Received error #{JSON.stringify err}"
            logger.error err.stack
        else
            for stack in data.StackSummaries
                    msg.send stack.StackName

module.exports = (robot) ->
    robot.hear /List running Cloudformation stacks/i, (msg)->
        msg.send "The following CloudFormation stacks are running:"
        getRegionStacks region, robot.logger, msg for region in defaultRegions.split ','

我期待输出看起来像:

The following CloudFormation stacks are running:
    In region us-east-1:
    demo-container1
    In region us-west-2:
    demo-container2
    In region eu-west-1:
    demo-container3

但是,看起来回调都是在函数完成后触发,返回的输出是:

The following CloudFormation stacks are running:
    In region us-east-1:
    In region us-west-2:
    In region eu-west-1:
    demo-container1
    demo-container2
    demo-container3

我确信我忽略了一些简单的事情。有没有人知道我做错了什么?

1 个答案:

答案 0 :(得分:0)

看起来您在liststacks函数异步时同步打印该区域。以下是未经测试但可能有效:

getRegionStacks = (region, logger, msg) ->
    AWS.config.region = region
    cloudFormation = new AWS.CloudFormation()
    params = {
        StackStatusFilter: [ 'CREATE_COMPLETE' ]
    }
    cloudFormation.listStacks params, (err, data) ->
        if err
            logger.error "Received error #{JSON.stringify err}"
            logger.error err.stack
        else
            msg.send "In region #{region}:"
            for stack in data.StackSummaries
                msg.send stack.StackName