【问题标题】:Koa 2. How can server response be sent 'from Promise' in router?Koa 2. 如何在路由器中“从 Promise”发送服务器响应?
【发布时间】:2016-09-16 22:45:59
【问题描述】:

这是作为 AJAX 请求的脚本执行的:

app.use(route.post('/ajax_request', function(ctx) {
    var p = new Promise(function(res){
        res('Some result to be received as AJAX resp');
    });
    p.then(function (val){
        ctx.body = val; //resolved after response is sent
    });
}))

那么如何将一些异步接收的(在这种情况下包装在 Promise 中)数据发送回客户端(在这种情况下作为 AJAX 响应)?

【问题讨论】:

    标签: ajax asynchronous promise koa


    【解决方案1】:

    如果您使用的是 Koa 2,则应该为中间件使用 async 函数。如果您不熟悉在 Koa 2 中使用 async/await 或任何其他 ES6+ 功能,我建议您学习如何使用 Babel 转译您的代码以允许使用它们。如果您不想进行转译步骤,您目前应该只使用 Koa 1.X。

    在 Koa 2 中,代码如下所示:

    app.use(route.post('/ajax_request', async (ctx) => {
        let p = new Promise(function(res){
            res('Some result to be received as AJAX resp');
        });
    
        let val = await p;
        ctx.body = val;
    }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-02
      • 2013-09-08
      • 1970-01-01
      相关资源
      最近更新 更多