【发布时间】:2020-08-07 17:35:07
【问题描述】:
我在 NestJs 中有一个 API,它不会在第一次点击时发送数据。但是,再次点击它时,它会发送所需的数据。我猜 API 在内部处理完成之前返回。
如何阻止这种情况。睡眠是一个很好的选择吗?
或者有没有其他方法可以做到这一点?
@Post("load")
@UseGuards(AuthGuard("jwt"))
async load(@Req() body: any)
{
const organizationId = body.user.organizationId;
const userId = body.user.userId;
if ("brandIds" in body.body)
{
await this.userService.onBoardUser(userId);
}
var settings = await this.settingsService.fetchLayout(organizationId, "home");
settings.forEach(async (element) =>
{
var parsedElement = JSON.parse(JSON.stringify(element));
var innerContent = await this.fetchContent(parsedElement.method, organizationId, userId);
var template = parsedElement.content[0];
let formattedItem = {};
innerContent.forEach((item) =>
{
try
{
formattedItem = template;
Object.keys(template).forEach((key) =>
{
if (template[key]!= "" && key != "type")
{
formattedItem[key] = eval(template[key]);
}
});
parsedElement.content.push(formattedItem);
formattedItem = null;
}
catch(err)
{
}
});
this.response.data.push(parsedElement);
innerContent = null;
template = null;
formattedItem = null;
parsedElement = null;
});
return(this.response);
}
【问题讨论】:
-
我想知道如果有人在处理结束之前遇到 API 返回的问题,我是否可以得到一个通用的答案。
-
@Talg123 编辑了问题并添加了上面的代码。请看一看。
-
好的,你需要明白你可以在foreach方法中使用async/await。将其更改为 for...of
标签: node.js api express nestjs