如何在异步函数中返回数字或错误(如果有)?

时间:2019-04-09 10:52:15

标签: node.js promise async-await

我正在尝试从异步函数获取结果,但是异步函数可以在promise中返回数字或错误(如果由我们的代码抛出)。

我试图从catch块抛出异常。但是我得到了Expression预期的TSLint错误。

private async insertAppOrg(orgId): Promise<number> {
    try {
       return this.dbInstance.AppOrg.find({where: {orgId: orgId}})
            .then(async (appOrgData) => {
                if (appOrgData) {
                    return appOrgData.appOrgId;
                } else {
                    return (await this.createAppOrg(orgId)); //return number 
                }
        });
    } catch (ex) {
        return throw new ErrorFactory.DatabaseError(ex);
    }
}

如果成功,此函数应返回orgId(number),否则应从catch块引发Exception。

2 个答案:

答案 0 :(得分:2)

return throw是语法错误,因为throw是语句,而不是表达式。

另一个问题是try..catch中的async..await无法处理返回的诺言中的错误,应该是:

 return await this.dbInstance.AppOrg.find(...).then(...)

由于thenasync的语法糖,因此无需在await函数中使用then

private async insertAppOrg(orgId): Promise<number> {
    try {
       const appOrgData = await this.dbInstance.AppOrg.find({where: {orgId: orgId}});
        if (appOrgData) {
            return appOrgData.appOrgId;
        } else {
            return (await this.createAppOrg(orgId));
        }
    } catch (ex) {
        throw new ErrorFactory.DatabaseError(ex);
    }
}

答案 1 :(得分:0)

您需要返回promise,并删除try-catch块。


private async insertAppOrg(orgId: number): Promise<number> {
  return this.dbInstance.AppOrg.find({ where: { orgId: orgId } })
      .then(async (appOrgData: any) => {
        if (appOrgData) {
          return appOrgData.appOrgId;
        } else {
          return (await this.createAppOrg(orgId));
        }
      })
      .catch((e: any) => {
        throw new Error("This is an error")
      });
}