我现在开始使用Node.js + Express,目前正在编写HTTP API结构。
我有一个使用以下模式公开一些方法的控制器: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?这可能吗?
也许这是一个愚蠢的问题,但是我仍然没有掌握诺言背后的概念。我来自.NET / Java,JavaScript(client)世界,因此我对JavaScript服务器端有些陌生。
无需进一步了解此特定上下文,.then()
就可以链接Promise的语句,其中一个.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: "..."}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句