2 回答
TA貢獻(xiàn)1860條經(jīng)驗 獲得超9個贊
如果你想使用 RxJS,你應(yīng)該在catchError與forkJoin.
const { of, from, forkJoin } = rxjs;
const { catchError, tap } = rxjs.operators;
// your promise factory, unchanged (just shorter)
const request = {
get: url => {
return new Promise((resolve, reject) => setTimeout(
() => url === '/urlnotexists' ? reject(new Error(url)) : resolve(url), 1000
));
}
};
// a single rxjs request with error handling
const fetch$ = url => {
console.log('before:', url);
return from(request.get(url)).pipe(
// add any additional operator that should be executed for each request here
tap(val => console.log('after:', val)),
catchError(error => {
console.log('err:', error.message);
return of(undefined);
})
);
};
// concurrently executed rxjs requests
forkJoin(["/urlexists", "/urlnotexists", "/urlexists2", "/urlexists3"].map(fetch$))
.subscribe(merged => console.log("merged:", merged));
<script src="https://unpkg.com/@reactivex/rxjs@6.5.3/dist/global/rxjs.umd.js"></script>
TA貢獻(xiàn)1789條經(jīng)驗 獲得超10個贊
如果你愿意放棄 RXJS 而只是用 async/await 解決它是非常簡單的:
const urls = ['/urlexists', '/urlnotexists', '/urlexists2', '/urlexists3']
const promises = urls.map(url => request(url)
const resolved = await Promise.allSettled(promises)
// print out errors
resolved.forEach((r, i) => {
if (r.status === "rejected') {
console.log(`${urls[i]} failed: ${r.reason})
}
})
// get the success results
const merged = resolved.filter(r => r.status === "resolved").map(r => r.value)
console.log('merged', merged)
這利用了Promise.allSettled提議的輔助方法。如果您的環(huán)境沒有此方法,則可以按照此答案中所示實現(xiàn)它。
添加回答
舉報
