@ expo/ 结果
一个高效、符合标准的库,用以代表操作成功或失败的结果。 结果对象代表一个能够成功返回一个值或失败的操作的结果. 通常我们要么返回一个值,要么扔出一个错误,但有时我们作为一个批次进行多个操作,有些可能成功,有些则失败. 由于我们无法同时返回值并抛出出出错,我们转而返回结果对象的集合. 这使得批量操作能够返回成功操作的值和失败操作的出错而不丢失信息,即出错. (对比之下,有时批量操作应该只返回成功值而省略失败操作的值. )
使用量
使用结果
import { Result, result } from '@expo/results';
const results = await fetchWebPages(['https://expo.dev', 'http://example.com']);
for (const result of results) {
if (result.ok) {
console.log(result.value);
} else {
console.error(result.reason);
}
}
创造结果
import { Result, result } from '@expo/results';
/**
* The purpose of this result API is to let you write functions that can
* partially succeed and partially fail and return all of that information to
* the caller.
*/
function fetchWebPages(urls: string[]): Promise<Result<string>[]> {
return Promise.all(urls.map(fetchWebPage));
}
function fetchWebPage(url: string): Promise<Result<string>> {
try {
const response = await fetch(url);
const text = await response.text();
return result(text);
} catch (e) {
return result(e);
}
}