4 回答

TA貢獻(xiàn)1874條經(jīng)驗(yàn) 獲得超12個(gè)贊
在過(guò)濾器承諾數(shù)組的情況下出現(xiàn)相同的錯(cuò)誤:
const promises = ids.map((id) => <some BE API call>);
const resolvedPromises = await Promise.allSettled(promises);
resolvedPromises.filter(({ status }) => status === 'fulfilled').map((p) => p.value);
問(wèn)題是allSettledreturns PromiseSettledResult,它根本沒(méi)有導(dǎo)出(我在 lib.es2020.promise 中使用tsconfig):
interface PromiseFulfilledResult<T> {
status: "fulfilled";
value: T;
}
interface PromiseRejectedResult {
status: "rejected";
reason: any;
}
type PromiseSettledResult<T> = PromiseFulfilledResult<T> | PromiseRejectedResult;
并且.map不明白所有的rejected承諾都在filtered方法中被過(guò)濾了。
所以,我什至無(wú)法導(dǎo)入類(lèi)型并將值轉(zhuǎn)換為它們。
作為臨時(shí)解決方案,我用注釋抑制了 ESLint 和 TSC 規(guī)則:
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
然后我PromiseFulfilledResult在項(xiàng)目中創(chuàng)建了相同的接口并使用了類(lèi)型轉(zhuǎn)換:
resolvedPromises.filter(({ status }) => status === 'fulfilled').map((p) => (p as PromiseFulfilledResult).value);
結(jié)果我擺脫了 on error 和 ESLint/TS rules ignoring comments。

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
你只有一個(gè)狀態(tài)滿(mǎn)足的值屬性,而你沒(méi)有檢查它。
所以使用我自己的例子,它可以固定如下:
const p1 = Promise.resolve(50);
const p2 = Promise.resolve(100);
const promiseArray = [p1, p2];
Promise.allSettled( promiseArray ).
then( results => results.forEach( result =>
console.log(result.status,
result.status === 'fulfilled' && result.value
);
));
它現(xiàn)在驗(yàn)證承諾是否已實(shí)現(xiàn),然后打印值(如果是的話(huà))。

TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
如果在調(diào)用該方法后進(jìn)行類(lèi)型聲明,則可以避免此錯(cuò)誤allSettled。例如,您可以立即為打字稿輸入一個(gè)類(lèi)型,如下所示:
const promises = await Promise.allSettled([
fetch(url).then((response) => response.json()),
fetch(url).then((response) => response.json()),
]) as {status: 'fulfilled' | 'rejected', value: SomeType}[];
之后它將正常工作:
const resolvedPromises = promises.filter(({ status }) => status === 'fulfilled');
const responses = resolvedPromises.map((promise) => promise.value);

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超13個(gè)贊
您可以只鍵入 cast 的結(jié)果Promise.allSettled,例如:
const [
someData,
otherData
] = (await Promise.allSettled([
this.someRepository.count(),
this.otherRepository.count(),
])) as PromiseFulfilledResult<number>[];
// will verify the promises, but ts doesn't get it
this.verify(someData, otherData)
console.log(otherData.value) // ts is okay
Number 是從 promise 返回的類(lèi)型,如果你想用不同的類(lèi)型輸入 promises,你也可以使用[PromiseFulfilledResult<number>, PromiseFulfilledResult<string>]
添加回答
舉報(bào)