3 回答
TA贡献1789条经验 获得超8个赞
reflect
:
const reflect = p => p.then(v => ({v, status: "fulfilled" }), e => ({e, status: "rejected" }));reflect(promise).then((v => { console.log(v.status);});
function reflect(promise){ return promise.then(function(v){ return {v:v, status: "resolved" }}, function(e){ return {e:e, status: "rejected" }});}reflect(promise).then(function(v){ console.log(v.status);});
var arr = [ fetch('index.html'), fetch('http://does-not-exist') ]Promise.all(arr.map(reflect)).then(function(results){ var success = results.filter(x => x.status === "resolved");});
TA贡献1936条经验 获得超6个赞
类似的答案,但更符合ES6的习惯:
const a = Promise.resolve(1);
const b = Promise.reject(new Error(2));
const c = Promise.resolve(3);
Promise.all([a, b, c].map(p => p.catch(e => e)))
.then(results => console.log(results)) // 1,Error: 2,3
.catch(e => console.log(e));
const console = { log: msg => div.innerHTML += msg + "<br>"};
<div id="div"></div>
undefined
typeof
result.message
, result.toString().startsWith("Error:")
TA贡献2021条经验 获得超8个赞
.catch
let a = new Promise((res, rej) => res('Resolved!')), b = new Promise((res, rej) => rej('Rejected!')), c = a.catch(e => { console.log('"a" failed.'); return e; }), d = b.catch(e => { console.log('"b" failed.'); return e; });Promise.all([c, d]) .then(result => console.log('Then', result)) // Then ["Resolved!", "Rejected!"] .catch(err => console.log('Catch', err));Promise.all([a.catch(e => e), b.catch(e => e)]) .then(result => console.log('Then', result)) // Then ["Resolved!", "Rejected!"] .catch(err => console.log('Catch', err));
const catchHandler = error => ({ payload: error, resolved: false });
> Promise.all([a, b].map(promise => promise.catch(catchHandler)) .then(results => console.log(results)) .catch(() => console.log('Promise.all failed'))< [ 'Resolved!', { payload: Promise, resolved: false } ]
const successHandler = result => ({ payload: result, resolved: true });
> Promise.all([a, b].map(result => result.then(successHandler).catch(catchHandler)) .then(results => console.log(results.filter(result => result.resolved)) .catch(() => console.log('Promise.all failed'))< [ 'Resolved!' ]
const reflect = promise => promise .then(successHandler) .catch(catchHander)
> Promise.all([a, b].map(result => result.then(successHandler).catch(catchHandler)) .then(results => console.log(results.filter(result => result.resolved)) .catch(() => console.log('Promise.all failed'))< [ 'Resolved!' ]
const a = Promise.resolve(new Error('Not beaking, just bad'));const b = Promise.reject(new Error('This actually didnt work'));
a.catch
> Promise.all([a, b].map(promise => promise.catch(e => e)) .then(results => console.log(results))< [ Error, Error ]
reflect
> Promise.all([a.catch(() => undefined), b.catch(() => undefined)]) .then((results) => console.log('Known values: ', results.filter(x => typeof x !== 'undefined')))< [ 'Resolved!' ]
const apiMethod = () => fetch() .catch(error => { console.log(error.message); throw error; });
reflect
.
添加回答
举报