最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Filter rejected Promises - Stack Overflow

programmeradmin0浏览0评论

I have an array of Promise objects where I want to map on and filter the rejected Promises.

Expected output:

const promises = [
  failedPromise,
  successPromise,
  successPromise,
];

const resolvedPromises = promises.map(promise => ???);

The resolvedPromises variable should container the output of the two successPromise promises.

How would I implement such algorithm?

I have an array of Promise objects where I want to map on and filter the rejected Promises.

Expected output:

const promises = [
  failedPromise,
  successPromise,
  successPromise,
];

const resolvedPromises = promises.map(promise => ???);

The resolvedPromises variable should container the output of the two successPromise promises.

How would I implement such algorithm?

Share Improve this question asked Jul 28, 2016 at 21:09 guidsenguidsen 2,4036 gold badges35 silver badges57 bronze badges 2
  • how are the failed differentiated from the non-failed? what do the two objects look like? – jcollum Commented Jul 28, 2016 at 21:13
  • Have a look over here. Notice that it's impossible to synchronously determine the state of a promise, so the best you will get is a promise for an array of fufilled promises (or their results) – Bergi Commented Jul 28, 2016 at 21:20
Add a ment  | 

1 Answer 1

Reset to default 11

You can't inspect standard promises in a synchronous way, so you cannot filter the array by their resolution status. But you can employ Promise.allSettled to get a list of outes. Thanks to @O-2 in the ments. Example code to get only resolved values:

const promises = [
  Promise.resolve(1),
  Promise.reject(2),
  Promise.resolve(3)
];


const resolvedPromises = Promise.allSettled(promises).then(
  values => values.filter(o => o.status === 'fulfilled').map(o => o.value)
);

resolvedPromises.then(values => console.log(values));

发布评论

评论列表(0)

  1. 暂无评论