我正在使用Json发送一个定义数组。我在异步函数中更改了数组的值。在控制台日志中,我看到了正确的定义,但在发送时却没有。
public async setDefinitions(): Promise<void> {
this.horizontalWordsHints[0] = await DefinitionGetter.setDefinition("hello", this.levelOfDifficulty);
console.log("In the array, the def is: " + this.horizontalWordsHints[0]);
}
这是发送网格的代码。
public sendHorizontalWordsHints(req: Request, res: Response, next: NextFunction): void {
this.newGrid.setDefinitions();
res.send(JSON.stringify(this.newGrid.horizontalWordsHints));
}
答案 0 :(得分:2)
原因是您在不等待响应的情况下呼叫this.newGrid.setDefinitions()
。所有async
个函数都会返回一个承诺,您必须await
才能通过then
和/或catch
获取或拒绝回复/拒绝。要执行前者,您可以将发送功能更改为:
public async sendHorizontalWordsHints(req: Request, res: Response, next: NextFunction): void {
await this.newGrid.setDefinitions();
res.send(JSON.stringify(this.newGrid.horizontalWordsHints));
}
要做后者:
public sendHorizontalWordsHints(req: Request, res: Response, next: NextFunction): void {
this.newGrid.setDefinitions()
.then(() => {
res.send(JSON.stringify(this.newGrid.horizontalWordsHints));
});
}