Async,有人吗?
尽管有大量的评论,但我没有找到使用异步映射器的解决方案。这是我的。
使用p-map,一个受信任的(@sindresorhus)和小的依赖关系。
(注意,没有选项传递给p-map。如果需要调整并发/错误处理,请参阅文档)。
字体:
import pMap from "p-map";
export const objectMapAsync = async <InputType, ResultType>(
object: { [s: string]: InputType } | ArrayLike<InputType>,
mapper: (input: InputType, key: string, index: number) => Promise<ResultType>
): Promise<{
[k: string]: ResultType;
}> => {
const mappedTuples = await pMap(
Object.entries(object),
async ([key, value], index) => {
const result = await mapper(value, key, index);
return [key, result];
}
);
return Object.fromEntries(mappedTuples);
};
普通JS:
import pMap from "p-map";
export const objectMapAsync = async (
object,
mapper
) => {
const mappedTuples = await pMap(
Object.entries(object),
async ([key, value], index) => {
const result = await mapper(value, key, index);
return [key, result];
}
);
return Object.fromEntries(mappedTuples);
};
};
用法示例:
(精心设计,无错误处理,无类型)
// Our object in question.
const ourFavouriteCharacters = {
me: "luke",
you: "vader",
everyone: "chewbacca",
};
// An async function operating on the object's values (in this case, strings)
const fetchCharacter = (charName) =>
fetch(`https://swapi.dev/api/people?search=${charName}`)
.then((res) => res.json())
.then((res) => res.results[0]);
// `objectMapAsync` will return the final mapped object to us
// (wrapped in a Promise)
objectMapAsync(ourFavouriteCharacters, fetchCharacter).then((res) =>
console.log(res)
);