来自Express的异步回调

时间:2015-11-19 15:40:20

标签: node.js express async.js

所以我需要的是一种让节点计算这个巨大的东西的方法,我想让它计算并立即返回202 Accepted,并通过Poller计算状态。有什么想法吗?

我的Node / Express端点中已有这样的场景:

<div class="list-group blog-archive">
    <% DateTime monthCounter = DateTime.Today.AddMonths(-6);
        for (int i = 0; i < 6; i++)
        {
            monthCounter = monthCounter.AddMonths(1);

            string monthHTML = "";
            string monthText = monthCounter.ToString("MMMM yyyy");
            string monthURL = "";
            string badgeHTML = "";
            string numberOfPostsInMonth = GetNumberOfPostsInMonth(monthCounter.ToString("MMMM"), monthCounter.ToString("yyyy"));

            //Bold the selected month list-item
            if (monthCounter.ToString("yyyy") == SelectedYear && monthCounter.ToString("MMMM") == SelectedMonth)
            {
                monthText = "<strong>" + monthText + "</strong>";
            }

            //If there are posts in the month, print the month as a link.
            //  Otherwise, if there are no posts in the month, print the month as a '<span>' rather than a link
            if (numberOfPostsInMonth != "")
            {
                monthURL = "BlogArchive?year=" + monthCounter.ToString("yyyy") + "&month=" + monthCounter.ToString("MMMM");
                badgeHTML = "<span class=\"badge\">" + numberOfPostsInMonth + "</span>";

                monthHTML = "<a href=\"" + monthURL + "\" class=\"list-group-item\">" + monthText + badgeHTML + "</a>";
            }
            else
            {
                monthHTML = "<span class=\"list-group-item\">" + monthText + badgeHTML + "</span>";
            }

            //Write the month list item to the page
            Response.Write(monthHTML);
        }
    %>
</div>

这可以按预期在后端进行单元测试,异步被触发,然后返回202,通过Poller API,我可以询问进度(在其他地方计算)。点是,一旦我在手动测试中从frontEnd执行此操作,module.export.poller = (req,res) -> res.status(200).send({ percentFinished: precentFinished }) module.export.beginHugeCalculation = (req,res) -> async.waterfall [ (next) -> # very, very, very, very time-intensive calculation here next null ], (err) -> # Success return # Immediately return HTTP 202 after Async Waterfall is triggered! # Status can be requested via Poller Route res.status(202).send({ inProgress : true }) return 被触发并返回202,并且我每秒发送的轮询器请求都排队并且仅在异步完成时立即返回所有请求在每个请求中回馈100%。

1 个答案:

答案 0 :(得分:2)

据我了解您的问题,您的应用的行为确实有意义。

因为您描述的大型计算是基于CPU的,并且节点在单个线程上运行,所以事件循环会卡住,因此不会处理新请求。

为了在进行大量计算时处理其他请求,您可以设置群集,或者,如果计算是递归的,则使用process.nexttick或setImmediate:setImmediate vs. nextTick

如果我遗漏了任何东西,请告诉我。