【问题标题】:Propagate rejected promise via a .catch()通过 .catch() 传播拒绝的承诺
【发布时间】:2017-10-15 22:46:09
【问题描述】:

我有一些基本上看起来像这样的代码:

export function firstFunction(req: express.Request, res: express.Response, next: express.NextFunction): void {
  secondFunction(id)
  .then((userId: UserId) => {
    res.status(200).send(UserId);
  })
  .catch((err) => {
    if (err instanceof NoResultError) {
      res.status(404).send(err);
    } else {
      next(err);
    }
  });
}


export function secondFunction(id: string): Promise<UserId> {
  return new Promise<UserId>((resolve, reject) => {
    thirdFunction(id)
    .then((data: TableInfo) => {
      if (Object.keys(data).length !== 3) {
        reject(new Error('data in database is not mapped properly'));
      }
      resolve(data);
    })
    .catch((err) => {
      // WANT TO PROPAGATE ERROR UP TO THE GETDETAILS FUNCTION WHICH CALLS THIS
    });
  });
}

export function thirdFunction(id: string): Promise<TableInfo> {
  return new Promise<TableInfo>((resolve, reject) => {
    let query = `
        //query goes here
    `;
    db.executeQuery(query, [id])
    .then((data: TableInfo) => {
      if (Object.keys(data).length < 1) {
        reject(new NoResultError('some message here'));
      }
      resolve(data);
    });
  });
}

我的目标是让三个函数中的最低级别 (thirdFunction) 确定来自 db-query 的数据是否找不到数据,然后以错误拒绝该承诺。然后 secondFunction 应该理想地捕获此错误并将其传播到 firstFunction 以便 firstFunction 可以正确处理该错误。我尝试过执行throw errreturn errreturn Promise.reject(err),所有这些都会导致未处理的承诺拒绝。我对这应该如何工作有什么(可能是根本的)误解?

【问题讨论】:

    标签: javascript node.js typescript promise


    【解决方案1】:

    secondFunction 理想情况下应该捕获此错误并将其向上传播

    不,传播是默认设置。理想情况下,您根本不需要捕捉它,它会自动传播。

    我已经尝试过所有导致未处理的承诺拒绝的事情。我的(可能是基本的)误解是什么?

    您正在使用Promise constructor antipattern!有了它,您需要在catch 处理程序中调用reject(err) 以使其工作。或者真的.then(resolve, reject);。但这绝对不是应该这样做的。

    相反,删除 new Promise 包装器并返回链接 then 处理程序的结果:

    export function secondFunction(id: string): Promise<UserId> {
      return thirdFunction(id)
      .then((data: TableInfo) => {
        if (Object.keys(data).length !== 3) {
          throw new Error('data in database is not mapped properly');
        }
        return getUserId(data);
      });
    }
    
    export function thirdFunction(id: string): Promise<TableInfo> {
      let query = `/* query goes here */`;
      return db.executeQuery(query, [id])
      .then((data: TableInfo) => {
        if (Object.keys(data).length < 1) {
          throw new NoResultError('some message here');
        }
        return data;
      });
    }
    

    【讨论】:

    • @Tomalak 是的,对,我只是复制了错误。固定。
    猜你喜欢
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 2019-08-31
    • 1970-01-01
    • 2016-08-23
    • 2019-11-25
    相关资源
    最近更新 更多