waitForAll(dependencies)

一个处理并发的帮手,你可以使用它来获得多个异步依赖的值。dependencies只能是一个 RdxValue的元组或者是一个属性由RdxValue组成的对象。


function waitForAll<
T extends RdxValue<any> | RdxValue<any>[] | { [key: string]: RdxValue<any> }
>(
dependencies: T,
set?: IRdxComputeSet<any>
): T extends RdxValue<infer P>
? RdxState<P>
: RdxState<
{
[P in keyof T]: UnwrapRdxValue<T[P]>;
}
>
export type UnwrapRdxValue<T> = T extends RdxState<infer R> ? R : never;

Example#

Root

The fallback content to display on prerendering
import React, { useCallback, useMemo } from 'react';
import {
compute,
useRdxState,
RdxContext,
useRdxStatus,
waitForAll,
isLoading,
useRdxValueLoader,
useRdxReset,
useRdxRefresh,
} from '@alife/rdx';
const pause = (t: number) => new Promise((resolve) => setTimeout(resolve, t));
const asyncCompute = compute({
id: 'asyncCompute',
get: async () => {
await pause(2000);
return '延迟2s的数据';
},
});
const asyncCompute2 = compute({
id: 'asyncCompute22222',
get: async () => {
await pause(4000);
return '延迟4s的数据';
},
});
export const Root = () => {
return (
<RdxContext>
<Counter />
</RdxContext>
);
};
const Counter = () => {
const waitCompute = useMemo(
() => waitForAll([asyncCompute, asyncCompute2]),
[]
);
const state = useRdxValueLoader(waitCompute);
const reset = useRdxReset(waitCompute);
return (
<div style={{}}>
{isLoading(state.status) ? (
<div>loading...</div>
) : (
<div>
state1:state.value[0]
<br />
state2:state.value[1]
</div>
)}
<button
onClick={() => {
reset();
}}
>
刷新
</button>
</div>
);
};