我正在开始使用 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: "..."}
关于javascript - Node.js 拦截 Promise 并阐述 Response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39179334/