typescript Promise.all()的类型

wn9m85ua  于 2022-11-26  发布在  TypeScript
关注(0)|答案(1)|浏览(213)

我无法弄清楚请求元组返回类型和Promise.all()之间的这些类型。
有什么想法吗?

  1. const createPromises = async (utteranceObject: Array<string[]>):
  2. Promise<Array<[string, Blob]>> => {
  3. const promises = utteranceObject.map((keyValue) => {
  4. return buildAudioFetchRequests(keyValue[0], keyValue[1]);
  5. });
  6. return Promise.all<Promise<[string, Blob]>[]>(promises);
  7. };
  8. const buildAudioFetchRequests = (key: string, url: string):
  9. [string, Promise<[string, Blob]>] => {
  10. return [key, useAuthenticatedFetch(url, { initialCache: false })];
  11. };

hgncfbus

hgncfbus1#

您在基于变量名称promises的代码中有一个误解。
buildAudioFetchRequests的返回类型不是一个promise,它是一个键和一个promise的元组。因为await不关心对象或数组的内容,所以await返回相同的元组。
基于所有其他返回类型,您似乎希望等待属于元组的所有返回承诺,因此改为如下所示:

  1. const createPromises = async (utteranceObject: Array<string[]>):
  2. Promise<Array<[string, Blob]>> => {
  3. // Rename this variable here
  4. const requests = utteranceObject.map((keyValue) => {
  5. return buildAudioFetchRequests(keyValue[0], keyValue[1]);
  6. });
  7. // Get the actual promise from the tuple
  8. const promises = requests.map((req) => req[1]);
  9. // You can even remove the explicit typing from here because it's all as intended now!
  10. return Promise.all(promises);
  11. };
  12. const buildAudioFetchRequests = (key: string, url: string):
  13. [string, Promise<[string, Blob]>] => {
  14. return [key, useAuthenticatedFetch(url, { initialCache: false })];
  15. };

根据伯吉的评论:
当你所做的只是忽略它的时候,为什么还要从buildAudioFetchRequests的元组中返回key呢?
如果确实没有在任何地方使用该函数返回值的键,也可以这样做:

  1. const createPromises = async (utteranceObject: Array<string[]>):
  2. Promise<Array<[string, Blob]>> => {
  3. const promises = utteranceObject.map((keyValue) => {
  4. return buildAudioFetchRequests(keyValue[0], keyValue[1]);
  5. });
  6. // Remove explicit typing here
  7. return Promise.all(promises);
  8. };
  9. const buildAudioFetchRequests = (key: string, url: string):
  10. // Change the returntype here
  11. Promise<[string, Blob]> => {
  12. // Change the return value here
  13. return useAuthenticatedFetch(url, { initialCache: false });
  14. };
展开查看全部

相关问题