วิธีใช้ Promise.allSettled กับ typescript?
การสร้าง typescript ล้มเหลวเนื่องจากดูเหมือนจะไม่เป็นเช่นPromise.allSetttledนั้นแม้ว่าฉันจะตั้งค่า ts config comilerOptions ด้วย"lib": [ "ES2020.Promise" ],
มันดูเหมือนกับว่าการตอบสนองสำหรับpromise.allSettledไม่รวมหรือresultreason
เมื่อเรียกใช้ typescript build ฉันได้รับข้อผิดพลาดต่อไปนี้:
Property 'reason' does not exist on type 'PromiseSettledResult<IMyPromiseResult>'.
และ
Property 'value' does not exist on type 'PromiseRejectedResult'.
บล็อกรหัสของฉันมีลักษณะเช่นนี้และอย่างที่คุณเห็นฉันพยายามเข้าถึงreasonและresultจากคำสัญญาที่ได้รับการแก้ไข
const myPromise = async () : Promise<IMyPromiseResult> {
return new Promise((resolve) => {
resolve("hello world")
})
}
const data = await Promise.allSettled([
myPromise()
]);
const response = data.find(res => res.status === 'fulfilled')?.result;
if(!response) {
const error = data.find(res => res.status === 'rejected')?.reason;
throw new Error(error);
}
ฉันจะอัปเดตคำประกาศ Promise.allSettled เพื่อรวมอินเทอร์เฟซที่ถูกต้องได้อย่างไร
คำตอบ
เช่นเดียวกับที่ Bergi กล่าวถึง TypeScript ไม่ทราบว่าเป็นประเภทPromiseFulfilledResult/ PromiseRejectedResultเมื่อตรวจสอบประเภท
วิธีเดียวคือโยนผลของสัญญา สามารถทำได้เนื่องจากคุณได้ตรวจสอบแล้วว่าสัญญาที่ได้รับการแก้ไขนั้นเป็นจริงหรือถูกปฏิเสธ
ดูตัวอย่างนี้:
const myPromise = async (): Promise<string> => {
return new Promise((resolve) => {
resolve("hello world");
});
};
const data = await Promise.allSettled([myPromise()]);
const response = (data.find(
(res) => res.status === "fulfilled"
) as PromiseFulfilledResult<string> | undefined)?.value;
if (!response) {
const error = (data.find(
(res) => res.status === "rejected"
) as PromiseRejectedResult | undefined)?.reason;
throw new Error(error);
}
กำหนดการfindเรียกกลับเป็น type guard ที่ส่งคืนเพรดิเคตประเภท:
type IMyPromiseResult = string
const response = data.find(
(res): res is PromiseFulfilledResult<string> => res.status === 'fulfilled'
)?.value;
if (!response) {
const error = data.find(
(res): res is PromiseRejectedResult => res.status === 'rejected'
)?.reason;
throw new Error(error);
}
สนามเด็กเล่นสาธิต