在Promise.all()中自定义被拒绝的响应

时间:2018-10-26 05:03:02

标签: javascript node.js reactjs es6-promise

嗨,我正在尝试自定义来自数组的诺言失败的错误响应

我已参考Handling errors in Promise.all并开发了以下代码 我可能需要对其进行调整以获得所需的响应。需要帮助

我实现了以下代码。请运行以查看输出

//User Data
const usersData = [{
    firstName: 'John',
    lastName: 'Smith',
    isResolved: true //I have this only to reject or resolve the promise
  },
  {
    firstName: 'Phil',
    lastName: 'Doe',
    isResolved: false
  },
  {
    firstName: 'Dan',
    lastName: 'Joe',
    isResolved: true
  }
]

//Promise which gets resolved
const delayResolveFunction = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const id = Math.floor((Math.random() * 10) + 1)
      resolve({
        userid: id,
        isSuccess: true
      })
    }, 100)

  })
}

// Promise which gets rejected
const delayRejectFunction = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const id = Math.floor((Math.random() * 10) + 1)
      reject({
        isSuccess: false
      })
    }, 100)

  })
}

//function which creates users based on whethere userid is present
const createUsers = (users) => {
  const promiseArray = [];
  users.forEach((user) => {
    let userId = user.id;

    if (!userId) {
      if (user.isResolved) {
        promiseArray.push(delayResolveFunction().then((response) => {
          userId = response.userid
          isSuccess = response.isSuccess
          return { ...user,
            userId,
            isSuccess
          }
        }))
      }
      if (!user.isResolved) {
        // statement is not executed because error is thrown
        promiseArray.push(delayRejectFunction().then((response) => {
          userId = response.userId
          return { ...user,
            userId
          }
        }))
      }

    } else return null;



  });
  // I have this logic to access the data even if one promise fails among three
  //If you look at the response object we can see request for second user failed


  // My question is can I also send user object for failed response?
  return Promise.all(promiseArray.map(p => p.catch((err) => {
    return err;
  })))
}


//mainfunction where array of promises are resolved
const mainFunction = async() => {
  try {
    const arrayOfPromises = await createUsers(usersData);
    console.log(arrayOfPromises)
  } catch (err) {
    console.log(err)
  }
}

mainFunction();

我希望获得如下输出

[{
    "firstName": "John",
    "lastName": "Smith",
    "isResolved": true,
    "userId": 3,
    "isSuccess": true
  },
  {
    //for failed response
    "firstName": 'Phil',
    "lastName": 'Doe',
    "isResolved": false,
    "isSuccess": false
  },
  {
    "firstName": "Dan",
    "lastName": "Joe",
    "isResolved": true,
    "userId": 8,
    "isSuccess": true
  }
]

如果您想看一下Codepen,这里是链接 https://codepen.io/punith77/pen/OBdLZa?editors=0012

请让我知道是否可以得到上述输出

2 个答案:

答案 0 :(得分:0)

使用陷阱,而不要在delayRejectFunction调用之后使用。并使用catch中的错误对象来获取isSuccess。我在下面发布了更改。

//User Data
const usersData = [{
    firstName: 'John',
    lastName: 'Smith',
    isResolved: true //I have this only to reject or resolve the promise
  },
  {
    firstName: 'Phil',
    lastName: 'Doe',
    isResolved: false
  },
  {
    firstName: 'Dan',
    lastName: 'Joe',
    isResolved: true
  }
]

//Promise which gets resolved
const delayResolveFunction = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const id = Math.floor((Math.random() * 10) + 1)
      resolve({
        userid: id,
        isSuccess: true
      })
    }, 100)

  })
}

// Promise which gets rejected
const delayRejectFunction = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject({
        isSuccess: false
      })
    }, 100)

  })
}

//function which creates users based on whethere userid is present
const createUsers = (users) => {
  const promiseArray = [];
  users.forEach((user) => {
    let userId = user.id;

    if (!userId) {
      if (user.isResolved) {
        promiseArray.push(delayResolveFunction().then((response) => {
          userId = response.userid
          isSuccess = response.isSuccess
          return { ...user,
            userId,
            isSuccess
          }
        }))
      }
      if (!user.isResolved) {
        // statement is not executed because error is thrown
        promiseArray.push(delayRejectFunction().catch((errorObj) => {
          var isSuccess = errorObj.isSuccess;
          return { ...user,
            isSuccess
          }
        }))
      }

    } else return null;



  });
  // I have this logic to access the data even if one promise fails among three
  //If you look at the response object we can see request for second user failed


  // My question is can I also send user object for failed response?
  return Promise.all(promiseArray.map(p => p.catch((err) => {
    return err;
  })))
}


//mainfunction where array of promises are resolved
const mainFunction = async() => {
  try {
    const arrayOfPromises = await createUsers(usersData);
    console.log(arrayOfPromises)
  } catch (err) {
    console.log(err)
  }
}

mainFunction();

希望这会有所帮助:)

答案 1 :(得分:0)

我不太确定此代码将在您的代码库中使用的位置,但是您可以进行这些更改

delayRejectFunction

// Promise which gets rejected
const delayRejectFunction = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const id = Math.floor((Math.random() * 10) + 1)
      reject({
        userid: id,
        isSuccess: false
      })
    }, 100)

  })
}

对delayRejectFunction的调用

// statement is not executed because error is thrown
promiseArray.push(delayRejectFunction().then((response) => {
  userId = response.userId
  return { ...user,
    userId
  }
}).catch(err => {
  userId = err.userid
  isSuccess = err.isSuccess
  return { ...user,
    userId,
    isSuccess
  }
}));