首页 > 解决方案 > NodeJS Promise Chaining:重用“then”并合并两个 Promise

问题描述

我有 2 个具有相同“then”和“catch”条件的 promise。如何根据条件将它们合并为单个承诺?

承诺 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);
        });
});

实现这一目标的最佳方法是什么?

标签: javascriptnode.jspromisemethod-chaining

解决方案


使用条件运算符,基于condition, 来确定初始Promise,然后调用.thenand .catch。另外,避免显式的 Promise 构造反模式

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

推荐阅读