javascript - Node.js 拦截 Promise 并阐述 Response

标签 javascript node.js express promise

我正在开始使用 Node.js + Express,目前我正在编写我的 HTTP API 结构。

我有一个 Controller ,它使用以下模式公开一些方法: my_controller.js

'use strict';
var AppApiFactory = function (express, appService) {

    var api = express.app;

    /* Get all apps ordered by Name Ascending */
    function getAllApps(request, response) {
        appService.getApps(request.query.$expand).then(function (apps) {
            response.status(200).send(apps);
            })
            .catch(function (err) {
                console.error('Error occurred in Apps Api: ' + err);
                response.status(500).send("" + err);
        });
    }

    /* Routing */
    api.get('/api/v1/apps', getAllApps);

    return {
        getAllApps: getAllApps,
    };
};

module.exports = AppApiFactory;

appService 是我的 ORM 返回的一个简单方法,它包括一个 Promise 和一个对象数组。 现在,因为我必须实现一些 ISO/RFC 标准,所以必须将响应转换为更复杂的结构,例如:

{
   "data":[my promise array],
   "count":10,
   "type":"xmlns:mytype..."
}

我如何拦截 ORM 返回的 Promise,修改内容并再次从我的 Express Controller 返回另一个 Promise? 这可能吗?

也许这是一个愚蠢的问题,但我仍然没有掌握 promise 背后的概念。 我来自 .NET/Java、JavaScript(客户端)世界,所以我对 JavaScript 服务器端有点陌生。

最佳答案

在不知道更多关于这个特定上下文的情况下,可以链接 Promise 的 .then() 语句,其中来自一个 .then() 调用的“thenable”流入下一个。

在您的情况下,它可能看起来像这样:

function getAllApps() {
  return appService
    .getApps(request.query.$expand)
    .then(function(apps) {
      response.status(200).send(apps);
      return {
        data: apps,
        count: apps.length,
        type: "xmlns:mytype..."
      }
    })
    .catch(...);
}

然后调用 getAllApps() 将返回一个 promise ,该 promise 从 appService.getApps() 获取原始响应并将其转换为您期望的格式。

getAllApps.then(function(response) {
  console.log(response);
});

// {data: [...], length: 10, type: "..."}

See this MDN article on Promise.prototype.then() for more .

关于javascript - Node.js 拦截 Promise 并阐述 Response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39179334/

相关文章:

javascript - 使用 concat 将对象添加到数组的正确方法

javascript - DROPDOWN 不想保持打开状态

javascript - 订购图像游戏

javascript - 如果我导出模块,如何在模块中分配变量

node.js - 如何将 token 从中间件传递到路由

node.js - Sequelize 。找到哪里有许多关联计数?

node.js - Passport-jwt token 过期

javascript - Highcharts:一次更新多个系列,以获得更流畅的动画

node.js - zsh:找不到命令:即使在我全局安装了express和express-generator之后也是如此

node.js - 在 Express.js 中,如何在没有 "response"对象的情况下渲染 Jade 局部 View ?