代码之家  ›  专栏  ›  技术社区  ›  Abhinav Tyagi

NodeJS承诺链:重用“then”并合并两个承诺

  •  0
  • Abhinav Tyagi  · 技术社区  · 6 年前

    我有两个相同的“然后”和“抓住”条件的承诺。如何根据条件将它们合并为单个承诺?

    承诺1

    return new Promise((resolve, reject) => {
        abc.getDataFromServer(resp1)
            .then((result) => {
                .....
                resolve();
            })
            .catch((error) => {
                .....
                reject(error);
            });
    });
    

    承诺2

    return new Promise((resolve, reject) => {
        abc.getDataFromDB(resp2)
            .then((result) => {
                .....
                resolve();
            })
            .catch((error) => {
                .....
                reject(error);
            });
    });
    

    所需承诺链

    return new Promise((resolve, reject) => {
        if(condition){
           abc.getDataFromServer(resp)
        }else{
           abc.getDataFromDB(resp2)
        }
            .then((result) => {
                .....
                resolve();
            })
            .catch((error) => {
                .....
                reject(error);
            });
    });
    

    1 回复  |  直到 6 年前
        1
  •  2
  •   CertainPerformance    6 年前

    使用条件运算符,基于 condition ,以确定初始值 Promise .then .catch 在上面。此外,避免使用 explicit Promise construction antipattern :

    return (condition ? abc.getDataFromServer(resp) : abc.getDataFromDB(resp2))
      .then((result) => {
          .....
          // instead of resolve(someTransformedResult):
          return someTransformedResult;
      })
      .catch((error) => {
          .....
          // instead of reject(error):
          throw error;
      });