如果使用异步函数,如何使用JSON发送属性

时间:2018-03-16 03:38:43

标签: json typescript asynchronous async-await

我正在使用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));
    }

1 个答案:

答案 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));
    });
}