我想多次调用我的api,然后只返回错误的对象(这里是工作对象)
您对此实施有何看法? (我不喜欢.then(()=> false
,但即使使用reduce也无法找到更好的实现方式)
我希望避免在Promise.all之后进行过滤
谢谢
updateWorkersStatusOnMissions: (workersOnMissions, apiService) => {
const updateWorkerStatusOnMissionPromises = workersOnMissions
.map(workerOnMission =>
apiService.put('missions', formatWorkerOnMission(workerOnMission))
.then(() => false)
.catch(() => formatWorkerInError(workerOnMission))
)
return Promise
.all(updateWorkerStatusOnMissionPromises)
.then(filter(Boolean))
},
答案 0 :(得分:1)
我通常要做的是在结果周围引入某种“框”,以告诉我从诺言中得到的结果的“种类”。一个promise总是会向您返回一个值,但是取决于提供它的位置then(onSuccess, onFail)
的类型是不同的。
const into = type => val => ({ type, val })
const arrayOfstuff = [];
const arrayOfPromises = arrayOfstuff.map(stuff => makePromise(stuff)
.then(into("success"), into("error")))
const successFullStruff = Promise.all(arrayOfPromises)
.then(filter(result => result.type === "success"))
const failedStuff = Promise.all(arrayOfPromises)
.then(filter(result => result.type === "error"))
答案 1 :(得分:0)
如果要基于谓词对列表/数组进行分区(在这种情况下,无论Promise是已解决还是被拒绝),请使用partition
!
const partitionP = coll => {
const resolved = [];
const rejected = [];
return Promise.all(coll.map(p => {
p.then(result => resolved.push(result)).catch(err => rejected.push(err));
}).then(_ => [resolved, rejected]);
});
async getApiResults = workersOnMissions => {
const [results, errors] = await partitionP(workersOnMissions.map(workerOnMission => {
return apiService.put('missions', formatWorkerOnMission(workerOnMission));
}));
// do something with the results/errors or just return them
};
您确实需要一个Promise分区,因为如果阵列中的任何Promises拒绝,Promise.all
将立即拒绝,这意味着您需要手动管理迭代(在这种情况下,请确保{{ 1}}的任何拒绝,并让他们回到快乐的道路上)。否则,您可以做一些更简单的事情,例如映射api调用以获取Promises数组,然后在.catch
处理程序中对结果进行分区。