toResult
将PromiseLike转换为Promise<Result>
217 bytes
currently in beta
使用方法
将 PromiseLike 转换为 Promise<Result>。
import { toResult, Result } from "radashi";
const good = async (): Promise<number> => 1;const bad = async (): Promise<number> => { throw new Error("bad");};
const goodResult = await toResult(good());// => [undefined, 1]
const badResult = await toResult(bad());// => [Error('bad'), undefined]抛出非 Error 值
如果给定的 promise 抛出非 Error 值,它将被重新抛出。这确保 Result 始终包含 Error 值或 undefined。
// 这不会捕获被拒绝的promise,因为它是// 用字符串而不是Error被拒绝的。const res = await toResult(Promise.reject("test error"));同步错误
此函数不会捕获同步错误。只有被拒绝的 promise 才会转换为 Err。
function bad() { if (Math.random() > 0.5) { // ⚠️ 这个错误不会被 `toResult` 捕获。要修复此问题,请在 // 包含函数中添加 `async` 关键字。 throw new Error("bad"); } return new Promise((resolve, reject) => { /* ... */ });}
const res = await toResult(bad());// ^? Promise<Result<number>>