我有一条路由,该路由应该是数据库中具有指标的REST api(它们是操作系统使用情况日志)。
目前,api仅返回json
数据标头,如下所示:
{"success":true,"message":"all os logs in database"}
API方法
const selectOsJSON = () => {
let os_JSONlogs = { "success":true,"message":"all os logs in database" };
let arrayLogs = [];
dbMethods.osModel.findAll( {raw : true,order: [['id','DESC']]} ).then( (data) => {
for(let entry of data)
{
arrayLogs.push(entry);
}
os_JSONlogs.data = arrayLogs;
console.log('REST API DATA:',os_JSONlogs);
} ).catch( (error) => console.log(chalk.redBright('Erreur de promesse REST API OS logs')) ); //need method to adequately shoot the JSON data.
return os_JSONlogs;
};
module.exports.selectOsJSON = selectOsJSON;
服务器示例路由:
app.get('/osjson',(request,response) => { //Should return JSON logs in REST API format
response.json(apiMethods.selectOsJSON());
response.end('oslog route - end');
});
如您所见,response.json直接添加数据,然后才能成功选择我要显示的记录。
我尝试使用经验很少的异步等待,或者创建了新的Promise,例如const selectOsJSON = new Promise(//)
,但都没有成功。
我想要实现的是一旦从findAll
查询中解析出数据后就发送response.json,这样我就可以拥有一个可以正常使用的rest API。
请指导我如何解决它。谢谢