我試圖從 React 鉤子內的多個承諾中獲得組合結果。但是當我使用鉤子時,該函式getAll立即回傳空,而不是回傳所有的MyTypes。
我的鉤子:(api.get回傳一個Promise<MyType[]>)
function useMyHook() {
const api = useApiService();
return {
getAll,
};
function getAll(arr: number[]): MyType[] {
const results: MyType[] = [];
for (const u of arr) {
api.get(u).then((res) => {
results.push(...res);
});
}
return [...new Set(results)];
}
}
用法:
function MyComponent() {
// ...
const myHook= useMyHook();
const use = () => {
// ...
const numbers = [1, 2, 3];
const myTypes = myHook.getAll(numbers);
const count = myTypes.length; // this will always be 0
// ...
};
}
我怎樣才能使這項作業?我已經嘗試了多個帶有 promise 鏈接和 async/await 的版本,但都無濟于事。
uj5u.com熱心網友回復:
由于api.get回傳了一個承諾,因此getAll也需要回傳一個承諾。它不能回傳 a MyType[],因為組裝該陣列需要時間。我會使用 Promise.all 創建一個新的承諾,它將等待單個承諾,然后有一些代碼來組合結果。
使用異步/等待:
function async getAll(arr: number[]): Promise<MyType[]> {
const promises: Promise<MyType[]>[] = [];
for (const u of arr) {
promises.push(api.get(u));
}
const results = await Promise.all(promises);
// results is an array of arrays, so we need to flatten it
return [...new Set(results.flat())];
}
// used like:
const use = async () => {
// ...
const numbers = [1, 2, 3];
const myTypes = await myHook.getAll(numbers);
const count = myTypes.length;
// ...
};
或者,如果您更喜歡使用.then:
function getAll(arr: number[]): Promise<MyType[]> {
const promises: Promise<MyType[]>[] = [];
for (const u of arr) {
promises.push(api.get(u));
}
return Promise.all(promises).then(results => {
// results is an array of arrays, so we need to flatten it
return [...new Set(results.flat())];
});
}
// used like:
const use = () => {
// ...
const numbers = [1, 2, 3];
myHook.getAll(numbers).then(myTypes => {
const count = myTypes.length;
// ...
});
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/371103.html
標籤:javascript 反应 反应钩子 es6-promise
